Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy another textbox value in real time Jquery

I want to get the value of another textbox and input it in realtime into the other textbox. HOW CAN I DETECT IF TEXT_3 WAS CHANGED? IF TEXT_3 VALUE CHANGED, IT MUST BE INPUTTED TO TEXT_4 For your convenience, here is the code and the demo:

**HTML**
    <label>TEXT 1: </label><input type="text" id="text_1" value=""/>
    <label>TEXT 2: </label><input type="text" id="text_2" value=""/>
    <label>TEXT 3: </label><input type="text" id="text_3" value=""/>
    <label>TEXT 4: </label><input type="text" id="text_4" value=""/>

**JAVASCRIPT**
    /* INPUT TEXT_1 AND TEXT_2 VALUE TO TEXT_3 ON TEXT_1 KEYUP*/
    $("#text_1").keyup(function() {
        $("#text_3").val($("#text_1").val() + " " + $("#text_2").val());
    })

    /* INPUT TEXT_1 AND TEXT_2 VALUE TO TEXT_3 ON TEXT_1 AND TEXT_2 KEYUP*/    
    $("#text_2").keyup(function(){
        $("#text_3").val($("#text_1").val() + " " + $("#text_2").val());
    })

    /* HOW CAN I  DETECT IF TEXT_3 WAS CHANGED? IF TEXT_3 VALUE CHANGED, IT MUST BE INPUTTED TO TEXT_4*/

    /* not working solution */   
    $("#text_3").change(function(){
        $("#text_4").val($("#text_3").val());
    })

DEMO: http://jsfiddle.net/8eXRx/7/

Thanks for responses!

like image 306
fart-y-goer Avatar asked Dec 12 '22 02:12

fart-y-goer


2 Answers

Add change() after your textbox3.val(), like below:

$("#text_1").keyup(function() {
    $("#text_3").val($("#text_1").val() + " " + $("#text_2").val()).change();
})

/* INPUT TEXT_1 AND TEXT_2 VALUE TO TEXT_3 ON TEXT_1 AND TEXT_2 KEYUP*/    
$("#text_2").keyup(function(){
    $("#text_3").val($("#text_1").val() + " " + $("#text_2").val()).change();
})

http://jsfiddle.net/8eXRx/12/

like image 88
Chris Li Avatar answered Dec 15 '22 00:12

Chris Li


The problem is that you can't bind special event to check that the textbox value was changed using JavaScript and not manually. To solve the task, one option is to use the same keyup event for both text_1 and text_2. JQuery will add the new handler to the existing handlers:

$("#text_1, #text_2").keyup(function(){
    $("#text_4").val($("#text_3").val());
})

DEMO: http://jsfiddle.net/8eXRx/11/

like image 39
VisioN Avatar answered Dec 15 '22 01:12

VisioN