简体   繁体   中英

Jquery .val() function not working on global scope

I have four radio buttons inside the div and want to store the value of the selected checkbox into a jquery variable. However the code is working fine inside the button scope. However if i declare the variable on the global scope(outside the button scope),the variable returns undefined Here is the jquery code that works fine

$(document).ready(function(){
  $('button').click(function(){
    var x=$('[name=user]:checked').val();
     alert(x);
  });
});

Here is the html code associated with it

<div class="first-section">
  <input type="radio" name="user" value="one">1</input>
  <input type="radio" name="user" value="two">2</input>
  <input type="radio" name="user" value="three">3</input>
  <input type="radio" name="user" value="four">4</input>
<button class="submit-one">Submit</button>
</div>

How to reuse this x variable in global scope. On declaring global it returns undefined. Here is the problematic code.

$(document).ready(function(){
var x=$('[name=user]:checked').val();
  $('button').click(function(){
     alert(x);
  });
});

//returns Undefined

you can declare global value x and then change it's value with in your function (in your example in.click() function)

$(document).ready(function(){
var x
  $('button').click(function(){
     x=$('[name=user]:checked').val();
     alert(x);
  });
});

You're declaring a variable inside a function, so it will not be accessible outside of the function.

If you want to access x outside of the function somewhere else you need to declare it outside of the function eg

var x;
$(document).ready(function(){
  $('button').click(function(){
     x = $('[name=user]:checked').val();
     alert(x);
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM