1

I have a hidden field with three integer values, example:

<input type="hidden" value="10 23 42">

I want to use jQuery to remove a given value, say "10", which would leave the remaining "23 42" value.

3 Answers 3

7
<script>
    $("input").val($("input").val().replace("10 ", ""));
</script>
Sign up to request clarification or add additional context in comments.

3 Comments

I'm certainly not diminishing this answer but it should be noted that it selects the element twice, which may be a performance concern.
You should be very careful with this as I think "10 23 42 310 15" would end up "23 42 3 15". Likewise if your value was "23 42 10" nothing would get replaced. You can still use .val to extract your value but I would recomend storing them as an array and using javascript to splice the propper element out before reasigning it.
Excellent point @jdcook72. I suggest using a regexp. /10 ?/ works as expected assuming only one occurrence of '10' to remove.
1

Basically the same as @Shaz answer but perhaps a little cleaner. This uses a function that returns the val to use. See the API docs at http://api.jquery.com/val/

$('input').val(function(index, val){
    return val.replace('10', '').trim();
});

To handle the possible trailing space after your integer:

val.replace(/10 ?/, '').trim()

Comments

-1
<input type="hidden" id="my_input" value = "10 23 42">
<script type="text/javascript">
jQuery(document).ready(function(){
     $("my_input").attr("value", $("my_input").attr("value").replace("10 ", ""));
});
</script>

1 Comment

You should use "val", It is more convenient and easier to read

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.