Alistair Norris
Alistair Norris

Reputation: 67

Text field to Hidden field value - value not being set

I'm having an issue with passing hidden values. I have a search field that onclick calls my javascript function with the intention of setting a hidden fields value further down the page.

    <div class="search">

        <input type="text" name="username" class="mySearch" value="">
        <input type="button" class="myButton" value="" onclick="setSearch();">

    </div>

My javascript, i is set outside of the function.

setSearch(){
    if(i == 0){
        $('input:hidden[name="search1"]').val($(".mySearch").val()); 
    }
    else if(i == 1)
    {
        $('input:hidden[name="search2"]').val($(".mySearch").val()); 
    }
    i++;
}

and then the field I'm try to set

<div class="sendallHolder">
    <form method="post" action="getTweets.php">

        <input type="hidden" name="fromTest" id="fromTest"/>
        <input type="hidden" name="untilTest" id="untilTest"/>
        <input type="hidden" name="latTest" id="latTest"/>
        <input type="hidden" name="longTest" id="longTest"/>
        <input type="hidden" name="search1" id="search1" />
        <input type="hidden" name="search2" id="search2" />


        <input type="submit" class="sendAll" value="Gather News!">
    </form>

</div>

It runs through the loop twice but each time its not setting the values properly in my hidden fields. the dev tools in chrome tell me that the 'value' is popping up but no value is being set. I'm not entirely sure what I'm doing wrong.

Any ideas?

Upvotes: 0

Views: 1724

Answers (3)

alessandrio
alessandrio

Reputation: 4370

$(".mySearch").keyup(addhjc);
function addhjc(){
        $('#search2').val($(".mySearch").val());
}

or

$('.myButton').click(function(){   
        $('#search2').val($(".mySearch").val()); 
});

also

function setSearch(){
    if(i === 0){........

and define i var

Upvotes: 0

Emrys Myrooin
Emrys Myrooin

Reputation: 2231

Use hidden input ID like this :

$('#search1').val($(".mySearch").val())

Upvotes: 3

Barmar
Barmar

Reputation: 782498

The :hidden selector doesn't do what you think. It matches elements that have been hidden using CSS, it doesn't match type="hidden" inputs. Just use

$("#search1")

since you have an id on the elements.

Upvotes: 4

Related Questions