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

Anna
  • 3
  • 2
  • You have three separate problems here (although the second will go away as a side effect of solving the third). See the duplicates. – Quentin Aug 05 '20 at 09:22
  • Please read: [mcve] the code in the question only needs 5 lines for the question as asked (and 2 of those are ``) – freedomn-m Aug 05 '20 at 09:31

1 Answers1

-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.

Bryn Lewis
  • 580
  • 1
  • 5
  • 14
  • What's wrong with `var scrt_var = document.getElementById("val").value;`? They already have that in the question. – Quentin Aug 05 '20 at 09:17
  • I understood the question to be about jquery not just javascript. – Bryn Lewis Aug 05 '20 at 09:19
  • 1
    To rephrase: How does replacing some plain DOM with jQuery that does exactly the same thing *solve the problem*? – Quentin Aug 05 '20 at 09:20
  • 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) – Bryn Lewis Aug 05 '20 at 09:51
  • 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. – Quentin Aug 05 '20 at 09:52
  • Only Input elements can return a "value". you are using
    here, which can return a text, or html only
    – Naveen Chandra Tiwari Aug 05 '20 at 12:55