Search code examples
jqueryprototypejs

Prototype or JQuery change the value of a hidden field?


I'm having some trouble with prototype changing the value of a hidden field.

Function:

function remove_fields (link) {
    $(link).next('input[type=hidden]').value = '';
    $(link).up(".open_hours").hide();
}

If I comment out the $(link).next('input[type=hidden]').value = ''; the hide function works. Trying to set the value gives me an error:

$(link).next("input[type=hidden]") is undefined

Here is my HTML around the function call:

    <div class="monday">

        <div class ="open_hours">
            <li><label for="location_monday">Monday</label>
            Open: 06:29PM - 
            Close: 04:21PM 
            <a href="#" onclick="remove_fields(this); return false;">remove</a></li>

            <li class="hidden optional" id="location_monday_open_input"><input id="location_monday_open" name="location[monday_open]" type="hidden" value="18:29:00" /></li>
            <li class="hidden optional" id="location_monday_close_input"><input class="close" id="location_monday_close" name="location[monday_close]" type="hidden" value="16:21:00" /></li>
  </div>    
</div>

Not sure what I'm doing wrong here? Thanks Guys!


Solution

  • jQuery based answer

    Since you have provided the input with an id, you can use the id selector

    $("#location_monday_close").val('');
    

    If you want to get the hidden element not based on the id then you can use something like

    $(link).closest('div.open_hours').find('input[type=hidden]').val('');
    

    Also if you want to hide the div with class name open_hours, you can use

    $("div.open_hours").hide();
    

    I have re written the code for you.

    $(function(){
        $("#anch1").click(function(){
            remove_fields ( $(this) );      
        });
    
        function remove_fields (link) 
        {
            var parentDiv = link.closest('div.open_hours');
            parentDiv.find('input[type=hidden]').val('');
            parentDiv.hide();
        }
    
    });
    
    <div class="monday">
        <div class ="open_hours">
            <li><label for="location_monday">Monday</label>
                Open: 06:29PM - 
                Close: 04:21PM 
                <a id="anch1" href="#" return false;">remove</a>
            </li>
            <li class="hidden optional" id="location_monday_open_input">
                <input id="location_monday_open" name="location[monday_open]" type="hidden" value="18:29:00" />
            </li>
            <li class="hidden optional" id="location_monday_close_input">
                <input class="close" id="location_monday_close" name="location[monday_close]" type="hidden" value="16:21:00" />
            </li>
        </div>    
    </div>
    

    Edit

    next finds the immediately following sibling of the selector(which is the anchor tag). In your HTML there is no next sibling for the anchor tag.