Reputation: 51100
I have put this at the top of my page (but within the body
tag).
<script type="text/javascript">
function displayNumberBounds(numberElement, number){
alert("it works");
$(numberElement).before("<input type='text' size='6' id='lower' value='"+number+"' class='lt'/> < ");
$(numberElement).after(" > <input type='text' size='6' id='upper' value='"+number+"' class='gt'/>");
}
</script>
and I have this further down (it's part of a template)
---- Edit ----
The way the code displays on the page is
.... some JavaScript/HTML here ....
<script type="text/javascript">
function displayNumberBounds(numberElement, number){
alert("it works");
$(numberElement).before("<input type='text' size='6' id='lower' value='"+number+"' class='lt'/> < ");
$(numberElement).after(" > <input type='text' size='6' id='upper' value='"+number+"' class='gt'/>");
}
</script>
.... more code here ...
<script>
$(document).ready(function() {
$(".number-value").click(function() {
displayNumberBounds(this,0);
});
});
</script>
0
... a loop iterates, thus giving the second value ...
<script>
$(document).ready(function() {
$(".number-value").click(function() {
displayNumberBounds(this,0);
});
}); 0
<script>
$(".number-value").click(function() {
displayNumberBounds(this,<%=number%>);
});
</script>
<span class="number-value" value="<%=number%>">
<%=number%>
</span>
Not sure if the extra info helps.
---------- end edit ---------
When I click the value that is printed by <%=number%>
I get the expected result for the first .number-value
item that is on the page but not for subsequent ones. I don't understand this.
Upvotes: 1
Views: 232
Reputation: 72652
Looks like you're trying to bind the click element when the element isn't loaded yet.
Can you try this please.
<script>
$(document).ready(function() {
$(".number-value").click(function() {
displayNumberBounds(this,$(this).html());
});
});
</script>
Check out this working example: http://jsfiddle.net/WS7Ha/
May I also suggest to you to move all Javascript to a separate .js file for maintainability.
Upvotes: 3
Reputation: 630379
You're re-binding quite a bit, (n
times), a better approach would be something like a data attribute, for example your template would look like this:
<span class="number-value" data-value="<%=number%>">
<%=number%>
</span>
Then once at the top of your page, bind to all of those, like this:
<script type="text/javascript">
$(document).ready(function() {
$(".number-value").click(function() {
var number = $(this).data("value");
$(this).before("<input type='text' size='6' id='lower' value='"+number+"' class='lt'/> < ")
.after(" > <input type='text' size='6' id='upper' value='"+number+"' class='gt'/>");
});
});
</script>
Or, it would be invalid HTML but use your current attribute, via .attr("value")
. Or, if the text always matches up you could just use $.trim($(this).text())
instead, with no attribute.
Upvotes: 2