0

I am new to jquery and javascript. I want to pass id="val" value to javascript's variable scrt_var. But my code returns undefined value.

Here is my code:

<script>
$('.value-plus').on('click', function () {
var divUpd = $(this).parent().find('.value'), newVal = parseInt(divUpd.text(), 10) + 1;
divUpd.text(newVal);
});

$('.value-minus').on('click', function () {
var divUpd = $(this).parent().find('.value'), newVal = parseInt(divUpd.text(), 10) - 1;
if (newVal >= 1)
divUpd.text(newVal);
});
</script>

<script>
var scrt_var = document.getElementById("val").value;
</script>

<div class="entry value-minus">&nbsp;</div>
<div id="val" class="entry value"><span>1</span></div>
<div class="entry value-plus active">&nbsp;</div>


<p><a class="item_add" href="addToCart.jsp?orderdetail=<%=orderId%>,<%=i.getItemID()%>,<%=c.getCategoryID()%>,<%=i.getPrice()%>," onclick="location.href = this.href + scrt_var;return false;">add to cart </a></p>

Output: addToCart.jsp?orderdetail=107,10,15,23.0,undefined

2
  • You have three separate problems here (although the second will go away as a side effect of solving the third). See the duplicates. Commented Aug 5, 2020 at 9:22
  • Please read: minimal reproducible example the code in the question only needs 5 lines for the question as asked (and 2 of those are <script></script>) Commented Aug 5, 2020 at 9:31

1 Answer 1

-1

For your div:


scrt_var = $('#val').text();

For input box:

scrt_var = $('#val').val();

val is not a great value to choose as an id.

Sign up to request clarification or add additional context in comments.

6 Comments

What's wrong with var scrt_var = document.getElementById("val").value;? They already have that in the question.
I understood the question to be about jquery not just javascript.
To rephrase: How does replacing some plain DOM with jQuery that does exactly the same thing solve the problem?
The don't do the same thing. the problem: document.getElementById("val").value; returns undefined (because divs don't have a value). The solution: $('#val').text(); (because they can have a text value, which is what Iunderstood was required)
I was referring to the second half of your answer (which was the only part when I made the comment since you edited it afterwards). Even the edit doesn't solve the problem because it is caused the intersection of three separate errors.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.