Duarte Arribas
Duarte Arribas

Reputation: 317

Can't change the button's value with jQuery

I'm trying to change the value of my button with jQuery.

This is what i have in html:

<button id="choice1">John</button>

And this is what I've tried to change the value:

$(document).ready(function(){
    $("#choice1").click(function(){
        $(this).val("Mike");  
    });
});

I even tried .attr / .prop / .html / .text instead of .val but none of them worked.

Ok so if I'm trying to change it to an Array like this:

var a = new Array(4000)

a[2][1] = "North"
a[2][2] = "South"
a[2][3] = "East"
a[2][4] = "West"

And the function:

function state1gmg(){
$(document).ready(function(){
    $("div#gamestatesdiv").text(state1);
});

$(document).ready(function(){
    $("div#questionsdiv").text(q[1]);
});

$(document).ready(function(){
    $("#choice1").click(function(){
        $(this).html(a[2][1]);  
    });
});

}

Any help? Thanks in Advance!!

Upvotes: 2

Views: 938

Answers (4)

P.S.
P.S.

Reputation: 16384

You should use text() or html() instead of val():

$(document).ready(function(){
    $("#choice1").click(function(){
        $(this).text("Mike");  
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="choice1">John</button>

Upvotes: 2

qiAlex
qiAlex

Reputation: 4346

$(document).ready(function(){
    $("#choice1").click(function(){
        $(this).val("Mike");  
        console.log ($(this).val()); // Mike. This changes value, but I suppose that you want to change inner text
        $(this).text("Mike");  // now the visible text will be Mike
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button id="choice1">John</button>

Upvotes: 2

Koby Douek
Koby Douek

Reputation: 16673

Changing a <button> value requires changing .text or .html.

In this snippet, .text works as expected:

$(document).ready(function(){
    $("#choice1").click(function(){
        $(this).text("Mike");  
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<button id="choice1">John</button>

Upvotes: 2

j08691
j08691

Reputation: 207900

You're changing the value alright, but what you want to do with a button (unlike an input) is to change the HTML (or text):

$(document).ready(function(){
    $("#choice1").click(function(){
        $(this).html("Mike");  
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="choice1">John</button>

Upvotes: 1

Related Questions