Question

I am looking to grab the value of a form input.

I think my problem is on this line:

    var vid = $(this).next(".pid").val();

I need to send the value of the input box named 'pid' to a php page, however there are several forms on the page, all with input boxes named 'pid'. When i merely have:

next(".pid").val();

the value that is sent is from another form on the page.

Edit: All I am really trying to do is set the "data" to be an array of all of the data in the form. So if there is a better way to set the "formdata" variable to the id of the form, that would work too.

Below is the jQuery function:

$(".varSel").live("change", function(){
    var vid = $(this).next(".pid").val();
    var formdata = $('form#addToCart'+ vid).serialize();
    $.ajax({
        type: "POST",
        url: "library/varPrice.php",
        data: formdata,
        success: function(html){
        $('.price').html(html);
      }
    });
});

EDIT:

Below is a form:

<form name='addToCart' id='addToCart99' action='cart.php?action=add' method='post'>
    <ul class='vars' id='varlist_p99'>
        <li>
        <label for="color">color</label> 
        <select id="color" name="color" class='varSel'>
            <option>blue</option>
            <option>green</option>
            <option>red</option>
        </select>
        </li>

        <li>
        <label for="size">size</label> 
        <select id="size" name="size" class='varSel'>
            <option>large</option>
            <option>small</option>
        </select>
        </li>

        <li>
            <div class='price'>
                $$
            </div>
        </li>

        <li>
                <input type='hidden' value='99' name='pid'> 
                <input type='submit' class='buynow' value=''>
        </li>
    </ul>
</form>
Was it helpful?

Solution

Replace this:

var vid = $(this).next(".pid").val();
var formdata = $('form#addToCart'+ vid).serialize();

With this:

var formdata = $(this).parents('form').serialize();

Tested and works.

OTHER TIPS

Why are you using next()?

You should try searching in the context:

$(".pid", this) // if "this" is the current form

Anyway I recommend to make every input with unique id attribute. So you don't have to guess which element will be processed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top