Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have a problem with a jQuery script on my MVC3 Website. The webpage has a hiddenfield that is bound to a property of the MVC model. When I click a h2 element of the page the onclick event will trigger a jQuery function that will update the hidden field.

Page:
HTML
@model XxxxxxMVC.Models.ProfielenZoekenModel
@using XxxxxxDLL
@{
    ViewBag.Title = "Zoeken";
}

@using (Html.BeginForm("", "profielen", FormMethod.Post, new { id = "profielen_form" }))
{
    @Html.HiddenFor(m => m.GeselecteerdeOpties)
    
    <!-- ...... some code ...... -->

    <h2  önclick="SwitchSelected('1');">Voorkeur Leeftijd</h2>

    <!-- ...... some code ...... -->

    <button type="submit">TOEPASSEN</button>
}


jQuery Script:
JavaScript
function SwitchSelected(id) {
    var key = "'" + id + "';";
    var ids = jQuery("#GeselecteerdeOpties").val();
    var loc = ids.indexOf(key);

    if (loc >= 0) {
        ids = ids.replace(key, '');
    }
    else {
        ids = ids + key;
    }

    jQuery("#GeselecteerdeOpties").val(ids);

    //alert(jQuery("#GeselecteerdeOpties").val());
}


This code above will work quite well, even after postbacks. But then out no where the system collapses and the hiddenfield doesn't get updated anymore.

If I then look at the jQuery with a debugger I can see that the jQuery function does get executed properly but the last code "jQuery("#GeselecteerdeOpties").val(ids);" doesn't change the hiddenfield at all. If I then debug it again I see that the jQuery code does see the changed hiddenfield with proper values in it, although the change can't be seen in the HTML of the page. So it's almost like the jQuery is updating a completely different page in memory or someting like that.


To make it even worse;

If I uncomment the last jQuery code "alert(jQuery("#GeselecteerdeOpties").val());", the problem doesn't occur anymore... :S



Any ideas?
Posted
Updated 10-Aug-12 4:34am
v3

1 solution

Are you sure you have only one html input with id='GeselecteerdeOpties' defined in the page? Seems like you have several inputs with same id.
Try updating the input by name attribute:
JavaScript
jQuery("input[name=GeselecteerdeOpties]").val(ids);

Doing so you'll update all GeselecteerdeOpties inputs.
 
Share this answer
 
Comments
willempipi 11-Aug-12 4:58am    
Worked! Thanks :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900