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.
Related
I am trying to create a dynamic Question List along with its dynamic options. With each option I maintain a flag using checkbox. If the checkbox is clicked the AnalysisFlag value should be true and if not then it should be false. However using the below mentioned method, I am always getting the false value whether I clicked the checkbox or not.
Can someone please take a look and suggest me how I can maintain the AnalysisFlag value along with its equivalent option?
function GetDynamicTextBox(value) {
var textBox = $("<input />").attr("type", "textbox").attr("name", "DynamicTextBox").attr("class", "form-control").attr("placeholder","Your Answer");
textBox.val(value);
debugger;
**var allVals = [];
$('[name="DynamicAnalysisFlag"]:checked').each(function () {
allVals.push($(this).val());
});**
return textBox, allVals;
}
var j = 66;
var x = 2;
var option = 'option' + x;
function AddTextBox() {
for (var i = j; i <= j; i++) {
$('#TextBoxContainer' + x).after("<br id='Removebr" + (x + 1) + "'><div class='input-group' id='TextBoxContainer" + (x + 1) + "'><div class= 'input-group-prepend'><div class='input-group-text'> " + String.fromCharCode(i) + " **<input type='checkbox' id='DynamicAnalysisFlag' value= 'true' name='DynamicAnalysisFlag' class='checklistitem''></div>**</div><input autocomplete='off' class='form-control test-option test-option" + x + " text-box single-line' data-val='true' data-val-required='Answer is required' id=" + option + " name='DynamicTextBox' placeholder='Your Answer' type='text' value=''><span class='field-validation-valid text-danger' data-valmsg-for='AnalysisFlag' data-valmsg-replace='true'></span></div>");
}
j++;
x++;
}
function RemoveTextBox() {
if (x != 2) {
$('#TextBoxContainer' + x).remove();
$('#Removebr' + x).remove();
--x;
--j;
}
}
$('#btnNext').on('click', function() {
var radioValue1 = $("input[name='AnalysisFlag']:checked").val();
var txtVal = $('.test-option' + radioValue1).val();
$('#hiddenRadioValue').val(txtVal);
});
$(function() {
var values = eval('#Html.Raw(ViewBag.Values)');
if (values != null) {
$("#TextBoxContainer").html("");
$(values).each(function() {
$("#TextBoxContainer").append(GetDynamicTextBox(this));
});
}
});
<div id="radio" class="col-xs-12">
<br id="Removebr2">
<div class="input-group" id="TextBoxContainer2">
<div class="input-group-prepend">
<div class="input-group-text">
A
<input type="checkbox" id="radio1" value="1" name="AnalysisFlag" onselect="alert('clicke')">
</div>
</div>
<input autocomplete="off" class="form-control test-option test-option1 text-box single-line" data-val="true" data-val-required="Option is required" id="opt1" name="opt1" placeholder="Your Answer" type="text" value="">
<span class="field-validation-valid text-danger" data-valmsg-for="opt1" data-valmsg-replace="true"></span>
<input data-val="true" data-val-required="The AnalysisFlag field is required." id="hiddenRadioValue" name="AnalysisFlag" type="hidden" value="">
<br>
</div>
</div>
<div class="card-footer">
<input type="submit" id="btnNext" value="Next ยป" class="btn btn-primary vigor-btn">
</div>
<button type="button" id="btnRemove" class="btn btn-primary vigor-btn" onclick="RemoveTextBox()">Remove Options</button>
<button type="button" id="btnAdd" class="btn btn-primary vigor-btn" onclick="AddTextBox()">Add Options</button>
I have edited the GetDynamicTextBox() function in which I am getting the DynamicAnalysisFlag value which I add at the time of adding another textbox in AddTextBox() function. But now the issue is, if I tick the checkbox I am getting the true value but if I don't tick the checkbox I am getting nothing. So, what changes should I do in this code so if I check the code, I get true and if not then I get false.
I am creating a JS form where i need 3 inputs from user and after typing the 3 inputs , on clicking 'Add record' button ,it should display them on the same page one after another (line by line) for every button click. With my code, it is writing every new input entry in the same line and not next line. How do i do it ?
My result:
Andrew Arts 2007 Evelyn Computers 2006
Expected result :
Andrew Arts 2007
Evelyn Computers 2006
function doSubmit() {
document.getElementById('f1').innerHTML += document.myform.name.value + " ";
document.getElementById('f1').innerHTML += document.myform.major.value + " ";
document.getElementById('f1').innerHTML += document.myform.year.value + " ";
return false;
}
<body>
<form name="myform">
<p>
Name: <input name="name" size="30" type="text" /> course: <input name="major" size="30" type="text" /> Year : <input name="year" size="4" type="text" />
</p>
<input type="button" value="Add record" onClick='doSubmit(); return false' />
</form>
<p id='f1'></p>
</body>
You use a <br> tag to break the line inside a <p> tag.
You just have to make a small change in your function :
function doSubmit() {
document.getElementById('f1').innerHTML += document.myform.name.value + " ";
document.getElementById('f1').innerHTML += document.myform.major.value + " ";
document.getElementById('f1').innerHTML += document.myform.year.value + " ";
document.getElementById('f1').innerHTML +='<br />'
return false;
}
If you're looking to style your form values , it would be good to append <p>tag for each form value . It will require a small change like below :
function doSubmit() {
document.getElementById('form-value').innerHTML += '<p>'+ document.myform.name.value + " " + document.myform.major.value + " " + document.myform.year.value + " " + "</p>";
return false;
}
Your HTML :
<body>
<form name="myform">
<p>
Name: <input name="name" size="30" type="text" /> course: <input name="major" size="30"
type="text" /> Year : <input name="year" size="4" type="text" />
</p>
<input type="button" value="Add record" onClick='doSubmit(); return false' />
</form>
<div id="form-value">
</div>
I would suggest creating a new p element for every submitted input. You also don't want to store the user input into the innerHTML, because it can lead to cross-site scripting attacks. To prevent this, you can use innerText instead. Here is an example of how you can achieve all that with your code:
function doSubmit() {
const newInputParagraph = document.createElement("p");
newInputParagraph.innerText += document.myform.name.value + " ";
newInputParagraph.innerText += document.myform.major.value + " ";
newInputParagraph.innerText += document.myform.year.value + " ";
document.getElementById("inputs").appendChild(newInputParagraph);
}
And you need to add container for input results (simple div) to your markup, for example like this:
<form name="myform">
<p>
Name: <input name="name" size="30" type="text" /> course: <input name="major" size="30" type="text" /> Year : <input name="year" size="4" type="text" />
</p>
<input type="button" value="Add record" onClick='doSubmit(); return false' />
</form>
<div id="inputs"></div>
I have an issue in showing filenanme to its corresponding field.
Now,
When i browse a file in the appended div,then it's file name is shown in the parent div instead of dynamically appended div.
Form
<!-- start other_docx -->
<div class="img_field">
<div class="j-row ">
<label class="j-label">Other Documents</label>
<div class="j-span9 j-unit">
<label class="j-input j-append-small-btn">
<label class="j-icon-left" for="files[]">
<i class="fa fa-download"></i>
</label>
<div class="j-file-button">
Browse
<!-- <input type="file" name="files[]" onchange="document.getElementById('files[]').value=this.value;"> -->
<input type="file" name="files[]" onchange="setfilename(this.value);">
</div>
<input type="text" id="files[]" readonly="" placeholder="No file selected">
<span class="j-hint">Only: jpg / png / Pdf</span>
</label>
</div>
<div class="j-span3 j-unit">
<div class="" style="margin-top:5px">
<button style="" class="btn btn-sm btn-primary add_more_button">Add more</button>
</div>
</div>
</div>
</div>
<!-- end other_docx -->
setfilename()
<script>
function setfilename(val)
{
var fileName = val.substr(val.lastIndexOf("\\")+1, val.length);
document.getElementById("files[]").value = fileName;
}
</script>
js
$(document).ready(function() {
var max_fields_limit = 10; //set limit for maximum input fields
var x = 1; //initialize counter for text box
$('.add_more_button').click(function(e){ //click event on add more fields button having class add_more_button
e.preventDefault();
if(x < max_fields_limit){ //check conditions
x++; //counter increment
// $('.img_field').append('<div><input type="file" name="files[]" class="form-control"/>Remove</div>'); //add input field
// var name="document.getElementById('files[]').value=this.value;";
$('.img_field').append('<div class="j-row">' +
'<div class="j-span9 j-unit">' +
'<label class="j-input j-append-small-btn">' +
'<label class="j-icon-left" for="files[]">' +
'<i class="fa fa-download"></i>' +
'</label>' +
'<div class="j-file-button"> Browse' +
'<input type="file" name="files[]" onchange="setfilename(this.value);">' +
// '<input type="file" name="files[]" onchange="'+name+'">' +
'</div>' +
'<input type="text" id="files[]" readonly="" placeholder="No file selected">' +
'<span class="j-hint">Only: jpg / png</span>' +
'</label>' +
'</div>' +
'<div class="j-span3 j-unit">' +
'<div class="" style="margin-top:5px">' +
'<button style="" class="btn btn-sm btn-danger remove_field">Remove</button>' +
'</div>' +
'</div>' +
'</div>');
}
});
$('.img_field').on("click",".remove_field", function(e){ //user click on remove text links
e.preventDefault();
// $(this).parent('div').remove();
$(this).closest("div.j-row").remove();
x--;
})
});
and this is what my form looks like..
enter image description here
I'm kinda new to jquery.. any help will be greatly appreciated.
Thank you in advance.!
//Edit
working fine now.I just replaced the id 'files[]' with a unique id for each dynamically created element.
Thanks to Ouroborus for mentioning the mistake.
Let's say I have div like this on my page:
<div style="padding-top:10px;" id="message2">
<p>More Links: <span class="fa fa-plus add"></span></p>
<div class="appending_div">
<div class="blog_links">
<p class="blog_linku_1">
Link URL 1: <input type="text" name="blog_linku_1[]"> Link Name 1: <input type="text" name="blog_linkn_1[]">
</p>
</div>
</div>
</div>
So simply if user click on + sign, it will add another input field just like this one with this script:
$(document).ready(function() {
var i = 2;
$('.add').on('click', function() {
var field = '<p class="link'+i+'">Link URL '+i+': <input type="text" name="blog_linku_'+i+'[]"> Link Name '+i+': <input type="text" name="blog_linkn_'+i+'[]"> <span class="glyphicon glyphicon-minus minus" id="minus'+i+'"></span></p>';
$('.appending_div').append(field);
i = i+1;
})
$('#minus'+i+'').click(function(){
$(".link"+i+"").remove();
});
})
And if you mention out, the extra links contains a remove symbol which is a - sign, and by clicking this sign, the paragraph which has the class link"+i+" should be removed.
And now the problem is that the remove icon does not work when you click on it. And the Console bar does not show any error message.
So what is your idea about this, how can I solve this problem?
First, it will be better to attach the event to a common class instead of using incremented values
Example :
var i = 2;
$('.add').on('click', function() {
var field = '<p class="link">Link URL ' + i + ': <input type="text" name="blog_linku[]"> Link Name ' + i + ': <input type="text" name="blog_linkn[]"> <span class="glyphicon glyphicon-minus minus">----</span></p>';
$('.appending_div').append(field);
i++;
});
NOTE: Since you're using input names as array [] you don't have to generate them with indexes.
You need to use the event delegation .on() when you attach the click event to .minus since the elements are generated dynamically :
$('body').on('click','.minus', function() {
$(this).closest('p').remove();
});
$(document).ready(function() {
var i = 2;
$('.add').on('click', function() {
var field = '<p class="link">Link URL ' + i + ': <input type="text" name="blog_linku[]"> Link Name ' + i + ': <input type="text" name="blog_linkn[]"> <span class="glyphicon glyphicon-minus minus">DELETE</span></p>';
$('.appending_div').append(field);
i++;
});
$('body').on('click', '.minus', function() {
$(this).closest('p').remove();
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="padding-top:10px;" id="message2">
<p>More Links: <span class="fa fa-plus add"></span></p>
<div class="appending_div">
<div class="blog_links">
<p class="blog_linku_1">
Link URL 1: <input type="text" name="blog_linku_1[]"> Link Name 1: <input type="text" name="blog_linkn_1[]">
</p>
</div>
</div>
</div>
<br>
<button class="add" type="button">Add</button>
I've restructured your code a bit. See below:
$(document).ready(function() {
var i = 2;
$('.add').on('click', function() {
$('<p class="link' + i + '">Link URL ' + i + ': <input type="text" name="blog_linku_[]" /> Link Name' + i + ': <input type="text" name="blog_linkn_[]"> <span class="fa fa-minus minus"></span></p>')
.appendTo('.appending_div');
i = i + 1;
});
$('.appending_div').on('click.remove', '.minus', function () {
$(this).parent()
.remove();
});
})
<link href="https://use.fontawesome.com/releases/v5.0.13/css/all.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="padding-top:10px;" id="message2">
<p>More Links: <span class="fa fa-plus add"></span></p>
<div class="appending_div">
<div class="blog_links">
<p class="blog_linku_1">
Link URL 1: <input type="text" name="blog_linku_1[]"> Link Name 1: <input type="text" name="blog_linkn_1[]">
</p>
</div>
</div>
</div>
I've simplified the top portion of your code that adds the element to the screen. Since you are using jQuery you can combine a few of these steps with the chaining of their library functions.
For the event handling, because the elements are added dynamically, you need to delegate the events to the new elements. Recall that elements must be present on the page for the event to be bound. Otherwise, the events must be delegated to an existing element. jQuery will handle the abstractions and the "bubbling" of the events to the parent element.
You are adding the #minus element on $(".add") click, so when the DOM loads it cannot find the $("#minus"). You have to add the $("#minus") click function inside the $(".add") click.
Try the below code
$(document).ready(function() {
var i = 2;
$('.add').on('click', function() {
var field = '<p class="link'+i+'">Link URL '+i+': <input type="text" name="blog_linku_'+i+'[]"> Link Name '+i+': <input type="text" name="blog_linkn_'+i+'[]"> <span class="glyphicon glyphicon-minus minus" id="minus'+i+'"></span></p>';
$('.appending_div').append(field);
i = i+1;
$('#minus'+i+'').click(function(){
$(".link"+i+"").remove();
});
});
});
I'm trying to take the user input of the form and on submit, populate a space in the DOM with the input. I also want to be able to print multiple user inputs in the same space (i.e. something like printing an array of user inputs onto the page each time a user submits)
function create_list_markup() {
document.getElementById("display").innerHTML =
"<h1 class='list-title'>"
+ document.getElementById('title').value + "</h1>"
+ "<br><br>"
+ "Recipient: "
+ document.getElementById('recipient').value
+ "<br>" + "Link: "
+ document.getElementById('link').value
+ "<br>"
+ "Price: "
+ document.getElementById('price').value;
}
function create_gift_markup(gift) {
const markup = `
<p>
<span class=''> ${gift.title} </span><br>
<span class=''> ${gift.recipient} </span><br>
<span class=''> ${gift.link} </span><br>
<span class=''> ${gift.price} </span><br>
</p>`;
return markup;
}
function insert_gifts(gift_markup) {
const gift_fragment = document.createDocumentFragment();
gift_markup.forEach(function __append_markup_to_docfrag(markup) {
let container_element = document.createElement('span');
container_element.insertAdjacentHTML('afterbegin', markup);
gift_fragment.appendChild(container_element.firstElementChild);
});
document.body.appendChild(gift_fragment);
}
function create_list_markup() {
const gift_markup = create_gift_markup(gifts)
insert_gifts(gift_markup)
}
The create_list_markup function works and prints out the user input to the screen (in conjunction with a div with an id of "display"), however I wanted to print multiple outputs to the same space, so I wrote the rest of the code. That's the stuff that doesn't work.
Here is the markup:
<h1>Christmas Gifts</h1>
<form class="gift-form" name="giftform" action="" id="gift">
<h2>Gift Submit Form</h2>
<label>Title of Gift</label>
<input type="text" name="title" value="" placeholder="Enter a title" id="title">
<label>Recipient of Gift</label>
<input type="text" name="recipient" value="" placeholder="Enter a recipient" id="recipient">
<label>Link to Gift Picture</label>
<input type="text" name="link" value="" placeholder="Enter link to picture" id="link">
<label>Price of Gift</label>
<input type="text" name="price" value="" placeholder="Enter price" id="price">
<button type="button" value="Submit" onClick="create_list_markup()">Submit</button>
</form>
<div class="list-box">
<h2>Gift List</h2>
<div id="display"></div>
</div>