I was trying to grab the ID of the SPAN tag when a user clicked it.
Since the ID of each tag contains two digits, they would be used for referring
to the value of their corresponding hidden text box field,
but I am stuck over this question.
Here is part of the code that I have written.
I need your help to finish it because I don't know how to move on.
<script type="text/javascript">
$(document).ready(function(){
$("#^=content").click(function(event){
// var digit = extract the last two digit of the id
var id_of_the_hidden_field = "hidden"+digit;
$("#show").val()=$("#hidden").val();
});
});
</script>
<div id="test22">
<span id="content22">Click to add the value</span>
<input type="hidden" id="hidden22" value="hello">
</div>
<div id="test33">
<span id="content33">Click to add the value</span>
<input type="hidden" id="hidden33" value="world">
</div>
<input type="text" id="show">
It would look like this:
$("[id^=content]").click(function(event){
$("#show").val($("#" + this.id.replace('content', 'hidden')).val());
});
You can test it here. There are a few corrections to this, first you need an attribute starts-with selector ([attr^=value]
) to find the elements by ID (though you could give the spans a class and use .class
as well). Then we're using the ID, replacing 'content'
with 'hidden'
via string.replace()
and grabbing input element by that ID. Also when setting a value use .val(value)
, .val() = value
isn't valid :)
If the structure is consistent you can make this much simpler, by relying on the fact that the <input type="hidden" />
is beside the <span>
like this:
$("[id^=content]").click(function(event){
$("#show").val($(this).next().val());
});
You cant test it here
As I said in the first example, if adding classed in an option it will makes your life easier, here's a version doing that:
<div id="test22">
<span id="content22" class="clickable">Click to add the value</span>
<input type="hidden" id="hidden22" value="hello">
</div>
<div id="test33">
<span id="content33" class="clickable">Click to add the value</span>
<input type="hidden" id="hidden33" value="world">
</div>
<input type="text" id="show">
and the jQuery:
$(".clickable").click(function(event){
$("#show").val($(this).next().val());
});
Here's that version in a demo
or
var digit = $(this).attr(id).substring(7, 9);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With