Dynamically adding and removing checkbox and inputfield - javascript

I want to make it possible to add and/or remove inputfields and a checkbox (for a competition-page)
Even though, when I click on the add button, 2 inputfields gets added and when i click the remove button, only on of those disappear. What is the issue?
var InputsWrapper = $("#answerDiv");
var AddButton = $(".adaddnext");
var x = InputsWrapper.length;
var FieldCount=1;
$(AddButton).click(function (e) {
FieldCount++;
$(InputsWrapper).append('<div class="adinputfield83"><div class="checkaccept cacc1"><label class="option"><input type="radio" id="contestAnswersChk_'+ FieldCount +'" name="correct" class="validate[required]"><span class="checkbox"></span></label> </div><input type="text" id="contestAnswer_'+ FieldCount +'" placeholder="Write possible answer" class="validate[required]"/><span class="font-entypo icon-circled-cross adaddnextremove" aria-hidden="true"></span></div></div>');
x++;
return false;
});
$("body").on("click",".adaddnextremove", function(e){
if( x > 1 ) {
$(this).parent('div').remove();
x--;
}
return false;
})
And the HTML:
<div id="answerDiv">
<div class="adinputfield83">
<div class="checkaccept cacc1">
<label class="option">
<input type="radio" id="contestAnswerChk_1" name="correct" class="validate[required]">
<span class="checkbox"></span>
</label>
</div>
<input type="text" id="contestAnswer_1" placeholder="Write possible answer" class="validate[required]">
<span class="font-entypo icon-plus adaddnext" aria-hidden="true"></span>
</input>
</div>
</div>
Can someone help me out? Thanks...

JSFiddle: http://jsfiddle.net/TrueBlueAussie/R3TLB/2/
You needed a delegated event for your add buttons as well as the delete buttons.
var InputsWrapper = $("#answerDiv");
var x = InputsWrapper.length;
var FieldCount = 1;
$(document).on('click', '.adaddnext', function (e) {
FieldCount++;
var template = $('#template').html();
template = template.replace(/{FieldCount}/g, FieldCount);
$(InputsWrapper).append(template);
x++;
return false;
});
$(document).on("click", ".adaddnextremove", function (e) {
if (x > 1) {
$(this).parent('div').remove();
x--;
}
return false;
})
HTML (using template HTML in dummy script block):
<script id="template" type="text/template">
<div class="adinputfield83">
<div class="checkaccept cacc1">
<label class="option">
<input type="radio" id="contestAnswersChk_{FieldCount}" name="correct" class="validate[required]" /><span class="checkbox"></span>
</label>
</div>
<input type="text" id="contestAnswer_{FieldCount}" placeholder="Write possible answer" class="validate[required]" /><span class="font-entypo icon-circled-cross adaddnextremove" aria-hidden="true">Del</span>
<input type="button" class="adaddnext" value="Add" />
</div>
</script>
<div id="answerDiv">
<div class="adinputfield83">
<div class="checkaccept cacc1">
<label class="option">
<input type="radio" id="contestAnswerChk_1" name="correct" class="validate[required]" /> <span class="checkbox"></span>
</label>
</div>
<input type="text" id="contestAnswer_1" placeholder="Write possible answer" class="validate[required]"> <span class="font-entypo icon-plus adaddnext" aria-hidden="true"></span>
</input>
</div>
<input type="button" class="adaddnext" value="Add" />
</div>
Notes:
Do not use $('body') to listen for delegated events. It can have odd side-effects with certain events (including click). Use a fallback of $(document) instead, if you do not have a closer non-changing ancestor to your dynamic elements. Really you should be using $('#answerDiv').on('click'... as that is the closest static ancestor (more efficient and more specific).

You have already defined you variables as selector $(...) so you should use only var names: AddButton.click()
The code looks then:
var InputsWrapper = $("#answerDiv");
var AddButton = $(".adaddnext");
var x = InputsWrapper.length;
var FieldCount=1;
AddButton.click(function (e) {
FieldCount++;
InputsWrapper.append('<div class="adinputfield83"><div class="checkaccept cacc1"><label class="option"><input type="radio" id="contestAnswersChk_'+ FieldCount +'" name="correct" class="validate[required]"><span class="checkbox"></span></label> </div><input type="text" id="contestAnswer_'+ FieldCount +'" placeholder="Write possible answer" class="validate[required]"/><span class="font-entypo icon-circled-cross adaddnextremove" aria-hidden="true"></span></div></div>');
x++;
return false;
});
$("body").on("click",".adaddnextremove", function(e){
if( x > 1 ) {
$(this).parent('div').remove();
x--;
}
return false;
})
or you can also define your variables as string, for example:
var AddButton = ".adaddnext"
then you can use it, as you did in your code:
$(AddButton).click(...)
Then is should look like:
var InputsWrapper = "#answerDiv";
var AddButton = ".adaddnext";
var x = InputsWrapper.length;
var FieldCount=1;
AddButton.click(function (e) {
FieldCount++;
InputsWrapper.append('<div class="adinputfield83"><div class="checkaccept cacc1"><label class="option"><input type="radio" id="contestAnswersChk_'+ FieldCount +'" name="correct" class="validate[required]"><span class="checkbox"></span></label> </div><input type="text" id="contestAnswer_'+ FieldCount +'" placeholder="Write possible answer" class="validate[required]"/><span class="font-entypo icon-circled-cross adaddnextremove" aria-hidden="true"></span></div></div>');
x++;
return false;
});
$("body").on("click",".adaddnextremove", function(e){
if( x > 1 ) {
$(this).parent('div').remove();
x--;
}
return false;
})

Related

getting values to populate a text instead of the span

I have pieced together a script that adds the values in text boxes and displays the sums in a span. I have tried a ton of things, but I can not get it to display the sums in a input textbox. Here is a fiddle that I have been working in ..
http://jsfiddle.net/elevationprint/MaK2k/17/
Basically I want to change the spans to input text boxes. If anyone can take a look and let me know what I am missing, I would appreciate it!
The code is this
HTML
Red<br>
12x12<input class="qty12" value="" /><br/>
12x24<input class="qty24" value="" /><br>
<br>
Blue<br>
12x12<input class="qty12" value="" /><br/>
12x24<input class="qty24" value="" /><br>
<br><br>
Total = <span class="qty12lable"></span> x $.95<br>
Total = <span class="qty24lable"></span> x $1.40<br>
SCRIPT
$('.qty12').keyup(function(){
var qty12Sum=0;
$('.qty12').each(function(){
if (this.value != "")
qty12Sum+=parseInt(this.value);
});
// alert('foo');
$(".qty12lable").text(qty12Sum);
//console.log(amountSum); });
$('.qty24').keyup(function(){
var qty24Sum=0;
$('.qty24').each(function(){
if (this.value != "")
qty24Sum+=parseInt(this.value);
});
// alert('foo');
$(".qty24lable").text(qty24Sum);
//console.log(amountSum); });
You can target the input fields like so:
Total = <input class="qty12lable" value=""> x $.95<br>
Total = <input class="qty24lable" value=""> x $1.40<br>
$("input.qty12lable").val(qty12Sum);
$("input.qty24lable").val(qty24Sum);
To set the text (value) of a textbox you have to use .val() not .text(). Like this:
$('.qty12').keyup(function() {
var qty12Sum = 0;
$('.qty12').each(function() {
if (this.value != "")
qty12Sum += parseInt(this.value);
});
$(".qty12lable").val(qty12Sum);
});
$('.qty24').keyup(function() {
var qty24Sum = 0;
$('.qty24').each(function() {
if (this.value != "")
qty24Sum += parseInt(this.value);
});
$(".qty24lable").val(qty24Sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Red
<br>12x12
<input class="qty12" value="" />
<br/>12x24
<input class="qty24" value="" />
<br>
<br>Blue
<br>12x12
<input class="qty12" value="" />
<br/>12x24
<input class="qty24" value="" />
<br>
<br>
<br>Total = <input class="qty12lable"/> x $.95
<br>Total = <input class="qty24lable"/> x $1.40
<br>
This snippet has some logic about how you can attach event listeners on input fields and how you can get their values. It's not perfect and has quite a few bugs from production level perspective but this will give a hint about how you can listen and manipulate DOM using Jquery. Which is what Jquery is all about.
$( "input" )
.change(function () {
var prevVal = ($('#total').html() !== '') ? $('#total').html() : 0;
if(parseInt($(this).val()) === NaN) {
return;
}
$('#total').html(parseInt($(this).val()) + parseInt(prevVal));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="1"></input><br>
<input type="text" id="2"></input><br>
<hr>
Total = <span id="total" class="qty12lable"></span> <br>

Dynamic textboxes are not removing

I am adding textboxes through jquery and for one text box it is removing perfeclty but when I add two textboxes then it does now remove both.
this is jquery
<script>
$(document).ready(function($){
$('.product-form .add-product').click(function(){
var n = $('.text-product').length + 1;
var product_html = $('<p class="text-product"><label for="product' + n + '">Name <span class="product-number">' + n + '</span></label> <input required type="text" name="productnames[]" value="" id="product' + n + '" /> <label for="productprice' + n + '">Price <span class="product-number">' + n + '</span></label> <input required type="text" name="productprices[]" value="" id="productprice' + n + '" />Remove</p>');
product_html.hide();
$('.product-form p.text-product:last').after(product_html);
product_html.fadeIn('slow');
return false;
});
$('.product-form').on('click', '.remove-category', function(){
$(this).parent().fadeOut("slow", function() {
$(this).remove();
$('.product-number').each(function(index){
$(this).text( index + 1 );
});
});
return false;
});
});
</script>
and this is my html
<div>
<form>
<div class="product-form">
<p class="text-product">
<label for="product1">Name <span class="product-number">1</span></label>
<input required type="text" name="productnames[]" value="" id="product1" />
<label for="product1">Price <span class="product-number">1</span></label>
<input required type="text" name="productprices[]" value="" id="product1" />
<div>
<a class="add-product" href="#">Add More</a>
</div>
</p>
</div>
<div>
<input type="submit" name="submitDetails" value="Finish"/>
</div>
</form>
</div>
If only one textbox for instance productnames is added then it removal function works but when I add botch productnames and productprices textbox removal function does not remove both
Your code should read $('.product-form').on('click', '.remove-product', function() rather than 'click', '.remove-category'. Also, don't place the Add More div element inside the paragraph element. The numbering also breaks a bit, but you can figure that out.

How to multiple (a*b) two input text value and show it Dynamicly with text change in javascript?

i want to show the money that customer must pay and my inputs are like this :
<input type="text" class="form-control" placeholder="cost " id="txt" name="credit">
<input type="text" class="form-control" placeholder="quantity" id="txt" name="limit">
when the input text is changing i want to show the total cost (quantity*cost) in a <p> tag Dynamicly how can it be with javascript?
You can try this:
<input type="text" class="form-control" placeholder="cost " id="credit" name="credit" onchange="calculate()">
<input type="text" class="form-control" placeholder="quantity" id="limit" name="limit" onchange="calculate()">
<p id="result"></p>
And javascript part:
function calculate() {
var cost = Number(document.getElementById("credit"));
var limit = Number(document.getElementById("limit"));
document.getElementById("result").innerHTML= cost*limit;
}
You must ensure you entered numbers in inputs.
All of the above will generate errors if both the boxes are blank . Try this code , its tested and running .
<script>
function calc()
{
var credit = document.getElementById("credit").value;
var limit = document.getElementById("limit").value;
if(credit == '' && limit != '')
{
document.getElementById("cost").innerHTML = parseInt(limit);
}
else if(limit == '' && credit != '')
{
document.getElementById("cost").innerHTML = parseInt(credit);
}
else if(limit!= '' && credit!= '')
{
document.getElementById("cost").innerHTML = parseInt(limit) * parseInt(credit);
}
else
{
document.getElementById("cost").innerHTML = '';
}
}
</script>
</head>
<input type="number" value="0" min="0" class="form-control" placeholder="cost" id="credit" name="credit" onkeyup="calc();">
<input type="number" value="0" min="0" class="form-control" placeholder="quantity" id="limit" name="limit" onkeyup="calc();">
<p id="cost"></p>
Hope this will be useful
// get cost field
var _cost = document.getElementById("cost");
_cost.addEventListener('keyup',function(event){
updateCost()
})
// get quantity field
var _quantity = document.getElementById("quantity");
_quantity.addEventListener('keyup',function(event){
updateCost()
})
function updateCost(){
var _getCost = document.getElementById("cost").value;
var _getQuantity = document.getElementById("quantity").value;
var _total = _getCost*_getQuantity;
console.log(_total);
document.getElementById("updateValue").textContent = ""; // Erase previous value
document.getElementById("updateValue").textContent = _total // update with new value
}
jsfiddle
In case you consider using JQuery I've made this fiddle.
See if it works for you.
https://fiddle.jshell.net/9cpbdegt/
$(document).ready(function() {
$('#credit').keyup(function() {
recalc();
});
$('#limit').keyup(function() {
recalc();
});
function recalc() {
var credit = $("#credit").val();
var limit = $("#limit").val();
var result = credit * limit;
$("#result").text(result);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control" placeholder="cost " id="credit" name="credit" value="0">x
<input type="text" class="form-control" placeholder="quantity" id="limit" name="limit" value="0">
<p id="result">0</p>
Try this:
<script >
function myFunction() {
document.getElementById('totalcost').innerHTML = document.getElementById('txt').value * document.getElementById('txt2').value;}
</script>
Also, change your HTML to this:
<input type="text" onkeypress="myFunction()" onkeyup="myFunction()" onclick="myFunction()" onmousemove="myFunction()" class="form-control" placeholder="cost " id="txt" name="credit">
<input type="text" onkeypress="myFunction()" onkeyup="myFunction()" onclick="myFunction()" onmousemove="myFunction()" class="form-control" placeholder="quantity" id="txt2" name="limit">
Enter cost and quantity.
Note the change with the second input: id='txt' was changed to id='txt2'. This is because no 2 elements can have the same id.
Note: Untested.

how to show hide based on this coding

HTML:
<input type="text" name="name" id="name_1" value="" class="showimage" />
<div class="icon_1" id="icon" style="display:none;"></div>
<input type="text" name="name" id="name_2" value="" class="showimage" />
<div class="icon_2" id="icon" style="display:none;"></div>
JQuery:
<script type="text/javascript">
$(document).ready(function() {
// Add onclick handler to checkbox w/id checkme
$('.showimage').click(function() {
var id = $(this).attr('id');
var ret = id.split("_");
var str1 = ret[1];
//alert(str1);
var id = $(this).attr('id');
var ret = id.split("_");
var str2 = ret[1];
//alert(str2);
//$(".icon_"+id).show();
// $("#icon").show();
if (str1 == str2) {
alert(str1);
$(".icon_" + str1).show();
//exit;
//alert("hi")
} else {
alert("sec");
$(".icon_" + str1).hide();
}
});
});
</script>
why not hide the else part
Your question: why not hide the else part?
That is because of $(this) it refers to the current element which have got the selector's context the event has raised on. So,
var id = $(this).attr('id');
The above variable has been used two times and both refers to the same object. So in the if condition:
if (str1 == str2) {
both values are always same and thus else never gets executed.
Better to use .focus()/.blur() events with .toggle(condition):
$(function(){
$('.showimage').on('focus blur', function(e){
$(this).next('div').toggle(e.type === "focus")
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="name" id="name_1" value="" class="showimage" />
<div class="icon_1" id="icon" style="display:none;">one</div><br>
<input type="text" name="name" id="name_2" value="" class="showimage" />
<div class="icon_2" id="icon" style="display:none;">two</div>
input[type="text"] {} input[type="text"] + div {
display: none;
}
hr {} input[type="text"]:focus + div {
display: inline-block;
/* added for style you can also use display:block */
}
<input type="text" name="name" id="name_1" value="" class="showimage" />
<div class="icon_1" id="icon">test1</div>
<hr>
<input type="text" name="name" id="name_2" value="" class="showimage" />
<div class="icon_2" id="icon">test2</div>

Unique Ids to bind radio buttons to text areas?

I have a form with multiple yes/no radio buttons and text area I would like to disable ("grey out") when yes is selected and enable when no is selected.
What I have currently only works for the first text area, all other radio buttons only effect the first text area because they have matching ids.
This is my view I am using.
#for (int i = 0; i < Model.Questions.Count; i++)
{
<tr>
<td>
<div>
#Html.RadioButtonFor(p => Model.Questions[i].AnswerSelected, true, new { id = "radio" + i, #class = "class" + i, value = "yes", }) Yes
#Html.RadioButtonFor(p => Model.Questions[i].AnswerSelected, false, new { id = "radio" + i, #class = "class" + i, value = "no" }) No
</div>
</td>
<td>
#Html.TextAreaFor(p => Model.Questions[i].ActionToTake, new { id = "text" + i })
</td>
</tr>
}
I know I will need to generate unique ids somehow for each pair of radio buttons and bind them to the text area somehow. This is the script I'm currently using.
$(document).ready(function() {
$(".class1").change(function (e) {
if ($(this).val() === 'True') {
$("#text1").prop('readonly', true);
$("#text1").css('background-color', '#EBEBE4');
} else if ($(this).val() === 'False') {
$("#text1").prop('readonly', false);
$("#text1").css('background-color', '#FFFFFF');
}
});
})
Whats a good way to approach this? I'm still new to javascript so any additional explanation for what you're doing would be helpful.
As I said in my comments, you do not need to have IDs unless you use them elsewhere. You can simply have a group, may be a DIV with a class and radio buttons and text area as the group children. Did you want something like this?
$(function() {
var $choices = $(".group").find(":radio");
$choices.on("change", function() {
var $this = $(this);
var choice = $.trim( $this.val() );
var tarea = $this.closest(".group").find("textarea");
tarea.prop("readOnly", choice === "yes");
if ( choice === "yes" ) {
//do your stuff when val = yes
} else {
//do your stuff when val = no
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="group">
<input type="radio" name="choice1" value="yes" />Yes
<input type="radio" name="choice1" value="no" />No
<textarea rows="4" cols="20"></textarea>
</div>
<div class="group">
<input type="radio" name="choice2" value="yes" />Yes
<input type="radio" name="choice2" value="no" />No
<textarea rows="4" cols="20"></textarea>
</div>
<div class="group">
<input type="radio" name="choice3" value="yes" />Yes
<input type="radio" name="choice3" value="no" />No
<textarea rows="4" cols="20"></textarea>
</div>
<div class="group">
<input type="radio" name="choice4" value="yes" />Yes
<input type="radio" name="choice4" value="no" />No
<textarea rows="4" cols="20"></textarea>
</div>

Categories

Resources