0

I would like to get the value of an input and return it to a span. I would like to update the span each time the input is changing. The problem is that i will use it for a colorpicker so the user will not usualy write the color value(maybe paste it). So everytime the input textfield will be updated by the colorpicker js i want to update my own field.

I created a simple code to help you understand what i want to do.

Pressing the + you will change the value of the input field and i would like to get that value and print it in the span. Thank you.

HTML ::

<div>
<input type="text" class="mariinsky" /><button id="inside">+</button>
</div>
<button id="outside">Button</button><br />
input value = <span></span>

JS ::

var i = 0;
jQuery('button#outside').click(function() {
    jQuery('div').toggle();
});

jQuery('button#inside').click(function() {
    jQuery( ".mariinsky" ).val(i);
    i++;
});

$( '.mariinsky' ).change( function() {
    var bolshoi = jQuery( ".mariinsky" ).val();
    jQuery( 'span' ).text(bolshoi);
});

http://jsfiddle.net/existence17/9V8ZU/1/

4 Answers4

1

Add .change() to the end of your '+' handler:

jQuery('button#inside').click(function() {
    jQuery( ".mariinsky" ).val(i).change();
    i++;
});

That will force the change event to fire and then your code will update the span.

Dean Ward
  • 4,793
  • 1
  • 29
  • 36
0

For live DOM changes, use the jQuery on function - the following code would work in your case:

var i = 0;
    jQuery('button#outside').click(function() {
        jQuery('div').toggle();
    });

    jQuery('button#inside').click(function() {
        jQuery( ".mariinsky" ).val(i);
        i++;
    });

    $( 'button#inside' ).on('click', function() {
        var bolshoi = jQuery( ".mariinsky" ).val();
        jQuery( 'span' ).text(bolshoi);
    });
nikjohn
  • 20,026
  • 14
  • 50
  • 86
0

jQuery doesn't automatically trigger events through code. You need to do so manually using the .trigger() method.

Adding one line did it for me: jQuery('.mariinsky').trigger("change").

Here's a working example: http://jsfiddle.net/9V8ZU/2/

Also a useful question for reference: How to trigger jQuery change event in code

Community
  • 1
  • 1
Alex P. Miller
  • 2,128
  • 1
  • 23
  • 20
0

please use this :

$( '.mariinsky' ).on('keypress keyup keydown click copy cut paste',  function() {
    var bolshoi = jQuery( ".mariinsky" ).val();
    jQuery( 'span' ).text(bolshoi);
});

Fiddle example

all the rest of the provided answers aren't covering the entire options.

Ori Refael
  • 2,888
  • 3
  • 37
  • 68