Jim
Jim

Reputation: 35

How to pass input value to button variable with jQuery

This is the code I am using which doesn't work. I want the value of "data-page" in the "button" to receive the value of the input field when the input field is blurred. The "data-page" is a number. Appreciate your assistance, thanks.

 <input type="text" value="" id="findR" />

 <button id="findRB" data-page="" >Find Record</button>

 <script>
  $(document).ready(function() {

     $( '#findR' ).blur(function() {
     $('#findRB[name=data-page]').val($('#findR').val());
     })

  });
 </script>

Upvotes: 0

Views: 62

Answers (4)

Cymen
Cymen

Reputation: 14419

Here is a working example:

 $(document).ready(function() {

     $( '#findR').blur(function() {
         $('#findRB').attr('data-page', $('#findR').val());
     });

  });

JSFiddle: http://jsfiddle.net/jyq2bm4r/

Upvotes: 0

Shaunak D
Shaunak D

Reputation: 20636

data-page is a data-* attribute and not name attribute.

$( '#findR' ).blur(function() {
    $('#findRB').data('page',this.value);
})

I would recommend using data(), but you won't see the actual attribute change as the value is stored in the DOM object. If you wish so, use attr()

$( '#findR' ).blur(function() {
    $('#findRB').attr('data-page',this.value);
})

Also, use this.value instead of $( '#findR' ).val() to set the value.

Upvotes: 1

Dinesh Patra
Dinesh Patra

Reputation: 1135

Hello can you please test this. This is working fine for me::

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>

<body>
    <input type="text" value="" id="findR" />
    <button id="findRB" data-page="" >Find Record</button>
    <script>
        $(document).ready(function() {
            $( '#findR' ).blur(function() {
                var inputVal = $('#findR').val();
                document.getElementById("findRB").setAttribute("data-page", inputVal);
            })
        });
    </script>
</body>
</html>

Upvotes: 0

murnax
murnax

Reputation: 1222

To set data attribute in element, you can use

$('findRB').attr('data-page', $('#findR').val());

Upvotes: 0

Related Questions