0

I have a javascript function meant to append the contents of a text field to a list, in order to make it render as soon as the user clicks a button next to the text field. The button and text field show up fine, but I've been told that I need to convert my function to JQuery, whose syntax I'm far less familiar with than javascript. This is the function:

document.getElementById("append").onclick = function()
{
    var text = document.getElementById("new-text").value;

    var li = "<li>" + text + "</li>";
    document.getElementById("list").appendChild(li);
}

list is the list I want to append the text field contents to, and new-text is the id for the text field content.

1
  • This may be water under the bridge, but why is someone asking you to "convert JavaScript to jQuery"? Do they even realize that jQuery is still Just JavaScript (TM)? Commented Sep 28, 2015 at 3:12

3 Answers 3

1

Try this:

$('#append').on('click', function () {
    var text = $('#new-text').val();
    var li = '<li>' + text + '</li>';
    $('#list').append(li);
});
Sign up to request clarification or add additional context in comments.

Comments

0

Why fix what ain't broke? jQuery is mostly useful as a time saver so you don't have to write out the longer vanilla javascript syntax, but I can't imagine a situation in which it should be required. Nevertheless:

$("#append").click(function()
{
    var text = $("#new-text").val();
    var li = $("<li>"+text+"</li>");
    $("#list").append(li);
});

Comments

0
$('#button').click(function () {
    var text = $('#text').val();
    var li;
    li = $('<li>' + text + '</li>');
    $("#ul").append(li);
})

You can have it like this. I named the button with the id button on the event that button is clicked it will get the value of textbox with the id text and then append it to the ul with the id ul.

DEMO

Or if you want to have the event called from a function you can have it like this

$('#button').click(function () {
   buttonclick();
})

function buttonclick(){
    var text = $('#text').val();
    var li;
    li = $('<li>' + text + '</li>');
    $("#ul").append(li);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.