简体   繁体   中英

Change value of a button when clicked

I have a list of jokes that I want to display in a box. When the page is loaded I want to display one at random in the box. Then when I click the box I want it to change the value again to another random one from the list.

At the moment I just cannot get it to work and can't work out where I am going wrong. I have the HTML as follows:

<input class="box" type="button" value"" />
<ul>
    <li>How much do pirates pay to get their ear pierced? &lt;/br&gt; A buck anear!</li>
    <li>How do pirates talk to one another? &lt;/br&gt; Aye to aye!</li>
    <li>What did the sea say to the pirate captain? &lt;/br&gt; Nothing, it justwaved!</li>
    <li>What is a pirates favourite shop? &lt;/br&gt; Ar-gos!</li>
    <li>When is it the best time for a pirate to buy a ship? &lt;/br&gt; Whenit is on sail!</li>
</ul>

The script is:

    $(document).ready(function () {

    var list = $("ul li").toArray();
    var elemlength = list.length;
    var randomnum = Math.floor(Math.random() * elemlength);
    var randomitem = list[randomnum];

    $('.box').click(function () {
        $(this).val(randomitem);
    });
});

Can someone please show me how to make the button have a value when the page is loaded and then change the value when the button is clicked.

Fiddle: http://jsfiddle.net/uRd6N/98/

Well you have two problems.

The first is that you are always selecting the same joke (determined when the page is loaded). The second is that you are adding the whole li element to the value of the button.

Try this:

$(document).ready(function () {
    var list = $("ul li").toArray();
    var elemlength = list.length;

    $('.box').click(function () {
        // get a new joke every time a button is clicked
        var randomnum = Math.floor(Math.random() * elemlength);
        var randomitem = list[randomnum].innerHTML; // use the HTML of the <li>
        $(this).val(randomitem);
    });
});

Live example: http://jsfiddle.net/NxdEc/

You don't need to load a jQuery object just to set a value. Also your randomitem needed to explicitely get the innerText of the li element

$(document).ready(function () {

    var list = $("ul li").toArray();
    var elemlength = list.length;
    var randomnum = Math.floor(Math.random() * elemlength);
    var randomitem = list[randomnum].innerText;

    $('.box').click(function () {
        this.value = randomitem;
    });
});

Substitute

$(this).val(randomitem);

with:

$(this).val($(randomitem).text());

PS: or even better

$(document).ready(function () {

    var list = $("ul li");
    var elemlength = list.length;
    var randomnum = Math.floor(Math.random() * elemlength);
    var randomitem = list.eq(randomnum);

    $('.box').click(function () {
        this.value = randomitem.text();
    });
});

PPS: if you wanted to make the button a div you could just do similarly:

$(document).ready(function () {

    var list = $("ul li");
    var elemlength = list.length;
    var randomnum = Math.floor(Math.random() * elemlength);
    var randomitem = list.eq(randomnum);

    $('.box').click(function () {
        $(this).html(randomitem.text());
    });
})

Just be sure to change the styiling of the div because it wouldn't look the same as that of an input.

You should make a few changes in your code:

  • Generate random value everytime you click the button. In your code random value is generated only once.
  • Assign element text, not the element itself, when clicking the button.
  • Set an initial value.

Random generation and assignment encapsualtion within a function would do great in your code. This code is working now (can run it at http://jsfiddle.net/uRd6N/99/ ):

$(document).ready(function () {
    var list = $("ul li").toArray();
    var elemlength = list.length;

    // Encapsulate random value assignment within a function
    var setRandomValue = function(element) {
            var randomnum = Math.floor(Math.random() * elemlength);
            var randomitem = list[randomnum];
            $(element).val($(randomitem).text());
    }

    // Bind click button
    $('.box').click(function () {
        setRandomValue(this);
    });

    // Set random value for the first time
    setRandomValue($('.box'));
});

Try this fiddle (It's a fork of yours): http://jsfiddle.net/darshanags/qHpkk/1/

HTML (update):

<input class="box" type="button" value="Value at page load" />

jQuery:

$(document).ready(function () {

  $('.box').click(function () {

    var $items = $("ul li"),
        list = $items.toArray(),
        elemlength = list.length,
        randomnum = Math.floor(Math.random() * elemlength);

     $(this).val($items.eq(randomnum).text());
  });
});

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