Laze Ho :
I have a little script which create a new div block if the user click on button. To count how many are created I have an hidden input. Everytime a new block is created the value of this hidden input should get updated.
Thats my script:
$(function () {
$("#addBtn3").on("click", function () {
imageBlockCount++;
document.getElementById("counter").value = imageBlockCount;
$(
$.parseHTML(
`<div class="form-group" id="gallery-${imageBlockCount}" >
<label for="new-content-${imageBlockCount}">New Content</label>
<input type="text" name="content-${imageBlockCount}" class="form-control" id="new-content-${imageBlockCount} test-${imageBlockCount}" placeholder="new content" required>
</div>`
)
).appendTo("#newElements");
});
});
This is my html code:
<div style="flex:auto;text-align:right;">
<button id="addBtn3" type="button">Content +</button>
</div>
<input name="counter" type="text" id="counter" value="0" hidden>
<div id="newElements">
</div>
But in the script where it should update the value don't work, but I don't know why, I don't find any other methods which are so different.
Ashkan :
Your code works fine. place console.log($("#counter").val())
after appendTo
.
A webpage's HTML doesn't automatically update when an input field's value changes.
If you want such functionality, you could place this after updating value of #counter
:
$('#counter').attr('value', $('#counter').val());
$(function () {
let imageBlockCount = 0
$("#addBtn3").on("click", function () {
imageBlockCount++;
document.getElementById("counter").value = imageBlockCount;
$('#counter').attr('value', $('#counter').val());
$(
$.parseHTML(
`<div class="form-group" id="gallery-${imageBlockCount}" <label for="new-content-${imageBlockCount}">New Content</label>
<input type="text" name="content-${imageBlockCount}" class="form-control" id="new-content-${imageBlockCount} test-${imageBlockCount}" placeholder="new content" required>
</div>`
)
).appendTo("#newElements");
console.log($('#counter').val())
});
});
<div style="flex:auto;text-align:right;">
<button id="addBtn3" type="button">Content +</button>
</div>
<input name="counter" type="text" id="counter" value="0" hidden>
<div id="newElements">
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=398724&siteId=1