How to Get & Set Input, Text, Select Value jQuery

jQuery val () Method – how to use this method with selected val elements. Here you will learn how use val() method.

We will take some examples using the val () method such as you can get selected box value using on jquery change. After get the value of selected box you can easily set the value of any input of text box using jquery val().

jQuery val() Method

There are uses of the jQuery val () method.

  • The val () method is used to get the value of the first element in the set of matching elements.
  • This is also used to set the value of each matching element.

Syntax

$(selector).val()  

It can use to get value.

$(selector).val(content)  

It can use to set value.

$(selector).val(function (index, currentcontent))  

This can use to set value using function.

Parameters of val() method

ParameterDescription
ValueThis is a mandatory parameter. This is used specify the value of the attribute.
Function (index, currentvalue)This is an optional parameter. This is used to specify a function that returns the value to set.

Example1 jQuery val() method

This val() method is work for to set a string of text, a number, an array of strings corresponding to the value of each matched element. It method lets you set the value by passing in the val() function.

<!DOCTYPE html>  
<html>  
<title>Learn Jquery val Method</title>
<head>  
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>   
<script>  
$(document).ready(function(){  
    $("#btn_click").click(function(){  
        $("#first").val("Hello there, this is example");  
    });  
});  
</script>  
</head>  
<body>  
<input type="text" id="first"> 
<br><br>  
<button id="btn_click">Click here to change the content</button>
</body>  
</html>  

Output

Learn Jquery value Method

Example 2 jQuery val() method

The val () method is mainly used to obtain the values ​​of form elements. In the below example, When we select a give select value then get the value of selected box and put the value of input box

<!DOCTYPE html>  
<html>  
<title>Learn Jquery value Method</title>
<head>  
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>  
<script> 
$(document).ready(function () {   
    $('body').on('change','#select', function() {
         $('#show_selected').val(this.value);
    });
});  
</script>    
</head>  
<body>  
<select id="select">
    <option value="">Select one</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
</select>
<br><br>  
<input type="text" id="show_selected">
</body>  
</html>  

Output

Learn Jquery value Method

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *