2

I have a code where I want a button's text to be stored in a variable and then set a text field's value to the text. Here's my code for the button onclick event:

$('#MyButton').click(function(){
        var user1 = $(this).attr("value");
        $('#MyTextField').val(user1);
    });

And Here is my button and text field:

<input type="text" class="form-control" id="MyTextField" aria-label="..." placeholder="User to send to">
 <button id="MyButton" class="btn btn-success" value="Go!">GO</button>

But nothing ever happens. Please help, Thanks in advance

EDIT regarding @Drakes

<script type="text/javascript">
var socket = io.connect('http://192.168.2.18:8080');
$(window).load(function(){
    username = "<%= user.local.email %>";
    console.log(username);
    socket.emit('join', username);
    socket.on('userjoino', function(data){
        $('#users').empty();
        $('#puser').empty();
        $.each(data, function(key, value){
            $('#users').append('<div class="alert alert-warning">'+key+'</div>');
            $('#puser').append('<li class="list-group-item" id="whisper" rec="'+key+'"> <button id="whisper" class="btn btn-success MyButton" value="'+ key + '">'+ key + '</button></li>');
        });
        var users = data;
        console.log(users);
    });
    $('form').submit(function(e){
        e.preventDefault();
        var message = $('#msg').val();
        if(message.length <= 0){
            $('#boxf').append('<div class="alert alert-danger">Message cannot be left empty</div>');
            var div = document.getElementById("boxf");
            div.scrollTop = div.scrollHeight;
        }else{
        //var msgob = [nickname + ': ' + message];
        //socket.emit('message', msgob);
        socket.emit('message', message);
        $('#boxf').append('<div class="alert alert-info"> Me: ' + message + '</div>' );
        var div = document.getElementById("boxf");
        div.scrollTop = div.scrollHeight;

        $('#msg').val('');
        }
  });
    socket.on('messages', function(data){
        $("#boxf").append('<div class="alert alert-info" >' + data + "</div>");
        var div = document.getElementById("boxf");
        div.scrollTop = div.scrollHeight;
        //document.getElementById('xyz').play();
    });
    socket.on('disuser', function(data){
        $("#boxf").append('<div class="alert alert-info">Server: ' +data+" has left the chat" + "</div>");
        var div = document.getElementById("boxf");
        div.scrollTop = div.scrollHeight;
    });

    $('#pm').click(function(e){
        var whisp = $('#whisp').val();
        var recipent = $('#recipent').val();
        console.log(recipent);
        socket.emit('whisper', {whisp: whisp, user: recipent});
        $('#whisp').val('');
        $('#recipent').val('');
        return false;
    });
    $('#whiisper').on('click', '.MyButton', function(){
        var user1 = $(this).val();
        $('#recipent').val(user1);
    });
    console.log('hey');
    socket.on('whisper', function(data){
        console.log(data);
        if(data.user === username){
            $('#messes').append('<div class="alert alert-info" >' + data.user + ': ' + data.whisp + "</div>");
        }else{
            console.log('ahaaaaahhh');
        }
    });

});
</script>

That is my script and here is how I have included JQuery:

<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script>
20
  • Try with $('#MyButton').on('click', function(){..} Commented Mar 29, 2015 at 9:06
  • Works here: http://jsfiddle.net/a6e979b4/. Probably you don't have jQuery included in your page? Commented Mar 29, 2015 at 9:07
  • Where is your JS code placed? Be sure it's inside of document.ready Commented Mar 29, 2015 at 9:08
  • 1
    @SaiAshwin you need to be more specific as to what's not working as in the fiddle, when you click on the button the value Go! gets set to the input! Commented Mar 29, 2015 at 9:09
  • 1
    By the way, you have '#whiisper' instead of '#whisper' if that is important Commented Mar 29, 2015 at 9:46

2 Answers 2

2

To handle events for dynamically added elements, you can use event delegation. You would need to bind the event to a containing element that exists from start.

If you have multiple elements, then the id doesn't work to identify them as it has to be unique, you would use a class instead.

To find the input element you would need to traverse the DOM to find the one next to the button.

Example:

$('#ButtonContainer').on('click', '.MyButton', function(){
    var user1 = $(this).val();
    $(this).prev().val(user1);
});

Make sure that the buttons has a class that you can use to recognise them. Example:

<div id="ButtonContainer">
  <input type="text" class="form-control" aria-label="..." placeholder="User to send to">
  <button class="MyButton btn btn-success" value="Go!">GO</button>
  <input type="text" class="form-control" aria-label="..." placeholder="User to send to">
  <button class="MyButton btn btn-success" value="Go!">GO</button>
  <input type="text" class="form-control" aria-label="..." placeholder="User to send to">
  <button class="MyButton btn btn-success" value="Go!">GO</button>
</div>

Demo, using dynamically added elements:

$('#ButtonContainer').on('click', '.MyButton', function(){
    var user1 = $(this).val();
    $(this).prev().val(user1);
});

$('#ButtonContainer').append('<input type="text" class="form-control" aria-label="..." placeholder="User to send to"><button class="MyButton btn btn-success" value="Go!">GO</button>');
$('#ButtonContainer').append('<input type="text" class="form-control" aria-label="..." placeholder="User to send to"><button class="MyButton btn btn-success" value="Go!">GO</button>');
$('#ButtonContainer').append('<input type="text" class="form-control" aria-label="..." placeholder="User to send to"><button class="MyButton btn btn-success" value="Go!">GO</button>');
<div id="ButtonContainer">
</div>

<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>

Sign up to request clarification or add additional context in comments.

8 Comments

Strange... It doesn't work on my machine..... But if i paste the exact code you have done... It works!!
@SaiAshwin: Verify that the code snippet works on your machine. Check for differences in the code, for example the use of classes.
Do the classes, the aria label and type, placeholder have to be in some sort of order? that is the only way my code is different
@SaiAshwin: No, the attribute order doesn't matter. Check that you don't have double class attributes, that one almost got me.
No double class attributes @Guffa
|
2

The code you posted is working with this scaffolding. When the "GO" button is clicked, "Go!" appears in the text input. Please make sure jQuery is included, and the MyButton button isn't dynamically created after the page loads.

<html>
<head>

<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script>

<script type='text/javascript'>
$(window).load(function(){
    $('#MyButton').click(function(){
        var user1 = $(this).attr("value");
        $('#MyTextField').val(user1);
    });
}); 

</script>

</head>
<body>
  <input type="text" class="form-control" id="MyTextField" aria-label="..." placeholder="User to send to">
  <button id="MyButton" class="btn btn-success" value="Go!">GO</button>
</body>
</html>

8 Comments

I checked everything... It still doesn't work! So srange
Could you try this code in an html file on your side to verify that it does what you would like? Then we can explore more trouble spots
strangely, that Works!
When and where do you execute the $('#MyButton').click(function() ... code? Could you post that section please?
Can you please head over to this fiddle and verify that the Go button is doing what you expect it to do? jsfiddle.net/Drakes/2345j2d9
|

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.