views:

126

answers:

2

I got a simple increment function like this:

  $(function(){
    $("#inc").click(function(){
        var value = parseInt($(":text[name='ice_id']").val()) + 1;
        $(":text[name='ice_id']").val(value);
    });
    $("#dec").click(function(){
        var value = parseInt($(":text[name='ice_id']").val()) - 1;
        $(":text[name='ice_id']").val(value);
    });
});

the ice_id text field is embedded within a form

<form id="masterSubmit" name="masterSubmit" action="" method="post">
     <td><input id="ice_id" type="text" name="ice_id" size="16" maxlength="15"></td>
</form>

When I try now to increment , it successfully increments a number, but shows the following weird behavior: It 'refreshes' the site, so that the content of the text field is gone. This behavior disappears, if I comment out the form tags ...unfortunately the form tags are required for an AJAX-submit.

Are there any ways to avoid this problem?

Thanks in advance for any hints and best regards

Daniyal

+3  A: 

just do a return false;

$(function(){
    $("#inc").click(function(){
        var value = parseInt($(":text[name='ice_id']").val()) + 1;
        $(":text[name='ice_id']").val(value);
        return false;
    });
    $("#dec").click(function(){
        var value = parseInt($(":text[name='ice_id']").val()) - 1;
        $(":text[name='ice_id']").val(value);
        return false;
    });
});

you may also improve your codes to:

$(function(){
    $("#inc").click(function(){

        $(":text[name='ice_id']").val(function(index, value) { return value++; });
        return false;

    });
    $("#dec").click(function(){

        $(":text[name='ice_id']").val(function(index, value) { return value--; });
        return false;

    });
});
Reigel
Works perfect. Thank's a lot! Aplologies, but could you explain me why "return false" leads to the removal of the previously weird behavior (or even how this behaviour has been triggered)?Best regardsDaniyal
Daniyal
I suspected you are using anchors or something that could navigate the page. By "return false", you are stopping the page navigation.... sorry if I confused you... :) not really good at explaining...
Reigel
by the way, if that solves your problem, please accept this one as an answer by clicking the check on the left... :) thanks!
Reigel
checked ;)japp, there was an anchor indeed,that has been used for an "accordion" system. Thank you for the explanation.
Daniyal
A: 

You can also try out the jQuery Increment plugin. I designed it for just such a purpose. In addition to your "inc" & "dec" elements, you can add keyboard (U/D arrow) and mousewheel support to your form input elements

Sean O
Thanks a lot and apologies for the late response. Due to some health issues I am now back :)
Daniyal