Reputation: 105
var x=0;
$(document).ready(function() {
$("div button").on("click", function(event) {
x = $(this).html();
}) ;
}) ;
console.log(x);
I have 5 buttons inside a div element I want the value of fhe button on click whrn they clicked by assigning it to a variable at outside of the function.
Upvotes: 0
Views: 748
Reputation: 773
So.. Erm.. What you want to do is.. When Button X is clicked, you want to use the X value as an Index in Arr[X] to display the contens of that in the LST block?
Since you are pulling the data as html, which is like a string of sorts, you need to do a cast to int first before using it as such, I guess.
It would probably be better to add the value as a property so you can write something else than a number on the button..
And don't forget that arrays count from 0, and your buttons count from 1, so you would need to subtract 1 to get the first element of arr. Or you could just add an empty element to your arr like:
var arr = [{rId:0, hNo:""}, ...
// In which case you wouldn't need to subtract 1.
In any case on point with your current line, it would be:
$('div button').click(function (event) {
var x = parseInt($(this).html()) - 1;
$('#lst').html(arr[x].rId + " " + arr[x].hNo);
});
If you were going to use the value of button it would be like:
HTML:
<button value='1'>Click this amazing button that blows your mind..</button>
Script:
$('div button').click(function () {
var x = $(this).val();
$('#lst').html(arr[x].rId + " " + arr[x].hNo);
});
If I got you right, that is.
Upvotes: 1
Reputation: 27041
When you correct all the small spelling errors then code actually works fine, as you can see I've moved the console.log(x)
inside your function so you can actually see that x is being set.
Var x=0;
=> var x=0;
$document. Ready(function() {
=> $(document).ready(function() {
$("div button"). On("click", function(event) {
=> $("div button").on("click", function(event) {
Console.log(x);
=> console.log(x);
var x = 0;
$(document).ready(function() {
$("div button").on("click", function(event) {
x = $(this).html();
console.log(x);
});
});
Note: if you are having problems getting the value of x outside the click function, then you need to provide us with more information about what you want to do with it or show us more of your jquery code.
demo
var x = 0;
var arr = [{rId: 1,hNo:"A31"},{rId: 2,hNo:"A32"},{rId: 2,hNo:"A33"}]
$(document).ready(function() {
$("div button").on("click", function(event) {
x = $(this).text().replace("button","");
document.getElementById("First").innerHTML = arr[x] != undefined ? arr[x].rId + " " + arr[x].hNo : "";
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<button>button1</button>
<button>button2</button>
<button>button3</button>
<button>button4</button>
<button>button5</button>
</div>
<div id="First"></div>
Upvotes: 0