Use html in JavaScript function - javascript

I face a little problem in below code.
I write below code. Unable to find out what's wrong in this code :
HTML:
<div class="all">
<div class="info">
<label>Degree <input type="text" class="row[0][degree]"></label>
<label>School <input type="text" class="row[0][school]"></label>
<label>Grade <input type="text" class="row[0][grade]"></label>
</div>
</div>
<button class="add_button" onclick="add_new()">Add Another</button>
JavaScipt:
var counter = 1;
function add_new() {
$('.all').append('
<div class="info">/
<label>Degree <input type="text" class="row[' + counter + '][degree]"></label>/
<label>School <input type="text" class="row[' + counter + '][school]"></label>/
<label>Grade <input type="text" class="row[' + counter + '][grade]"></label>/
</div>'
counter++;
);
}

Your counter variable doesnt have any relevence, since it is declared locally. If you want to increment the counter each time when calling this function, declare it globally. Also there are some syntax errors in the code, Your code should look like
var counter = 0;
function add_new() {
$('.all').append('<div class="info">\
<label>Degree <input type="text" class="row[' + counter + '][degree]"></label>\
<label>School <input type="text" class="row[' + counter + '][school]"></label>\
<label>Grade <input type="text" class="row[' + counter + '][grade]"></label>\
</div>'
);
counter++;
}

Try counter increment after closing the .append() method.

Instead of using onclick,do it like this with clean way:
HTML:
<button class="add_button">Add Another</button>
JQUERY:
$(document).ready(function(){
var counter = 0;
$(".add_button").click(function(){
$('.all').append('
<div class="info">/
<label>Degree <input type="text" class="row['+counter+'][degree]"></label>/
<label>School <input type="text" class="row['+counter+'][school]"></label>/
<label>Grade <input type="text" class="row['+counter+'][grade]"></label>/
</div>'
);
counter++;
});
})

counter has to be global and incremented outside of $.append
var counter = 0;
function add_new(){
$('.all').append('<div class="info"><label>Degree <input type="text" class="row['+counter+'][degree]"></label><label>School <input type="text" class="row['+counter+'][school]"></label><label>Grade <input type="text" class="row['+counter+'][grade]"></label></div>');
counter++;
}
JSFiddle

One way you can append HTML into the DOM without worrying about really long strings is:
$('.all').append(
$('<div class="info"/>').html(
$('<label/>').html( 'Degree ' ).append('<input type="text" class="row[' + counter + '][degree]">')
)
.append(
$('<label/>').html( 'School ' ).append( '<input type="text" class="row[' + counter + '][school]">' )
)
.append(
$('<label/>').html( 'Grade ' ).append( '<input type="text" class="row[' + counter + '][grade]">' )
)
);
It may be a few more lines, but I find it cleaner, easier to read (when your mind is in JS/jQuery mode) and easier to code .... ... as you can see if there's an object it's quite easy to iterate the object and generate the required HTML

Related

Appending a new field with unique id

I have code which takes a name and a number. I want to have a button that, when you click it, adds another field for another name and number, but it should have a different id because I need to use it for later.
So far, I have the code below but it doesn't work.
function addField() {
var id = 2
var name = 'Name of Owner # ' + id
var phonenum = 'Phone number'
$('.form-group').append('<br><label for="' + id + '">' + name + ':</label><input type="text" class="form-control" name="NewPnOwner" id="NewPnOwner' + id + '" />')
$('.form-group').append('<br><label for="' + id + '">' + phonenum + ':</label><input type="number" class="form-control" name="NewPnNumber" id="NewPnNumber' + id + '"/>')
id++;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group col-sm-4">
<fieldset>
<legend>
<code>New Phone Number</code>
</legend>
<label for="NewPnOwner">Name of Owner #1: </label>
<input type="text" class="form-control" name="NewPnOwner" id="NewPnOwner" />
<br />
<label for="Phonenumber">Phone number: </label>
<input type="number" class="form-control" name="NewPnNumber" id="NewPnNumber" />
<br />
<input type="button" id="button" value="Add New Field" onclick="addField()" />
</fieldset>
</div>
Just define id outside the function like this, otherwise it will initialize with value 2 on every call of addField().
var id = 2
function addField() {
var name = 'Name of Owner # ' + id
var phonenum = 'Phone number'
$('.form-group').append('<br><label for="' + id + '">' + name + ':</label><input type="text" class="form-control" name="NewPnOwner" id="NewPnOwner' + id + '" />')
$('.form-group').append('<br><label for="' + id + '">' + phonenum + ':</label><input type="number" class="form-control" name="NewPnNumber" id="NewPnNumber' + id + '"/>')
id++;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group col-sm-4">
<fieldset>
<legend><code>New Phone Number</code></legend>
<label for="NewPnOwner">Name of Owner #1: </label>
<input type="text" class="form-control" name="NewPnOwner" id="NewPnOwner">
<br>
<label for="Phonenumber">Phone number: </label>
<input type="number" class="form-control" name="NewPnNumber" id="NewPnNumber" />
<br>
<input type="button" id="button" value="Add New Field" onclick="addField()" />
</fieldset>
</div>
But
even though that this is the correct solution to your problem, I would not recommend you to give them ids like that. I can't think of any valid reason to solve any problem like so. There are probably better solutions for your real problem.

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.

Removing dynamically created divs with jquery

EDIT: Just so I asks questions better next time. I got a -1 what did I do wrong?
I'm adding quite a lot of html dynamically and want to be able to remove them also one by one.
Below the JQuery. I want to be able to remove the whole $("#row1' + (counter) + '") div including all divs in it by clicking the remove button under it.
Here's a fiddle: http://jsfiddle.net/FullContCoder/Sf9r5/1/
Thanks a lot in advance!
$(document).ready(function() {
var counter = 0;
$(".addButton").click(function() {
var test = $( '<div id="row1' + (counter) + '" class="row"><div class="col-md-2"><p><small>Placement Name:</small></p><input id="inputPlacement' + (counter) + '" type="text" class="form-control input-sm" name="placementName" placeholder="ex: Homepage">' +
'</div><div class="col-md-3"><p><small>URL:</small></p><input id="inputURL" type="url" class="form-control input-sm" name="url" placeholder="ex: http://www.allure.com"></div>' +
'<div class="col-md-2"><div class="row"><div class="col-md-12"><p><small>Select a Date and Time:</small></p></div></div><div class="row"><div class="col-md-12">' +
'<div class="input-append date" id="dp3" data-date="12-02-2012" data-date-format="dd-mm-yyyy"><input class="span2" size="16" type="text" value="12-02-2012" readonly=""><span class="add-on"><i class="icon-calendar"></i>' +
'</span></div></div></div><div class="row"><div class="input-append bootstrap-timepicker"><input id="timepicker1" type="text" class="input-small"><span class="add-on">' +
'<i class="glyphicon glyphicon-time"></i></span></div></div></div><div class="col-md-2"><p><small>Recurring:</small></p><select id="recurring" class="form-control input-sm">' +
'<option name="daily" value="daily">Daily</option><option name="weekly" value="weekly">Weekly</option><option name="month" value="month">Month</option></select></div>' +
'<div class="col-md-2"><p><small>Day of Week:</small></p><div class="row"><div class="col-md-6"><label class="checkbox-inline"><input id="mon" name="test" type="checkbox" value="1"> Mon</label>' +
'</div><div class="col-md-6"><label class="checkbox-inline"><input id="fri" name="test" type="checkbox" value="1"> Fri</label></div></div><div class="row"><div class="col-md-6">' +
'<label class="checkbox-inline"><input id="tue" name="test" type="checkbox" value="1"> Tue</label></div><div class="col-md-6"><label class="checkbox-inline">' +
'<input id="sat" name="test" type="checkbox" value="1"> Sat</label></div></div><div class="row"><div class="col-md-6"><label class="checkbox-inline">' +
'<input id="wen" name="test" type="checkbox" value="1"> Wed</label></div><div class="col-md-6"><label class="checkbox-inline">' +
'<input id="sun" name="test" type="checkbox" value="1"> Sun</label></div></div><div class="row"><div class="col-md-6"><label class="checkbox-inline">' +
'<input id="thu" name="test" type="checkbox" value="1"> Thu</label></div></div></div><div class="col-md-1"><p><small>Remove:</small></p>' +
'<button type="button" class="removeButton btn btn-default btn-sm"><span class="glyphicon glyphicon-minus-sign"></span></button></div></div>' )
$('.removeButton').click(function() {
$("#row1' + (counter) + '").remove();
});
counter++;
$("#row1").after(test);
});
});
You should use event delegation to add events to dynamically created elements. And use .closest() to get the first element that matches the selector. Try this:
$(document).on('click','.removeButton',function() {
$(this).closest("div.row").remove();
});
You need to move your remove button click handler outside of add button click handler.
DEMO
You can try it.
$(document).on('click', '.removeButton', function(){
$('#row1' + counter).remove();
});
1) You need to use event delegation here to bind click event to your button since it has been added dynamically to the DOM.
2) Use .closest() to remove the closest matching ancestor .row and remove redundant counter variable here:
3) You also need to move your click handler of remove button outside of the click handler of the add button.
Final code should look something like this:
$(document).ready(function () {
$(".addButton").click(function () {
var test = .....
$("#row1").after(test);
});
$('.removeButton').click(function () {
$(this).closest(".row").remove();
});
});
Updated Fiddle

Loosing margin with javascript jquery

Why when I add the same html code with javascript jquery I loose margin ?
Try this jsfiddle and you will understand me.
jQuery
function addphone() {
$( "#phonedetails" ).append( '<div >' +
'<label>phone :</label>' +
'<input type="text" /> ' +
'<input type="button" onclick="addphone()"/>' +
'</div>');
}
HTML
<div id="phonedetails">
<div>
<label>phone :</label>
<input type="text" />
<input type="button" onclick="addphone();"/>
</div>
</div>
It isn't a margin, it is a space (i.e. what you get when you press the space bar) between the label and the input. It is missing in the code generated from JS.
Change:
'<label>phone :</label>' +
To:
'<label>phone :</label> ' +
// ^ space here
You aren't losing margins, you're losing whitespace:
http://jsfiddle.net/3md9S/2/
$( "#phonedetails" ).append( '<div >' +
'<label>phone :</label> ' + // SINGLE SPACE ADDED HERE
'<input type="text" /> ' +
'<input type="button" onclick="addphone()"/>' +
'</div>');
That is just a white space in your html.
Also you don't have to write html again to append , you can clone it -
$( "#phonedetails" ).append($('#phonedetails div').eq(0).clone());
Demo --> http://jsfiddle.net/3md9S/7/

Add and remove inputs dynamicly with a other input

I searched a lot for this, but I can only find +1 -1 solutions.
But I want to set the number of inputs with a other input like this:
//Enter the number of inputs (1 is the start-value)
<input type="text" size="3" maxlength="3" id="count" name="count" value="1">
//Display that number of inputs (1 at start)
<input type="text" size="30" maxlength="30" id="input_1" name="input_1">
When the user now writes 5 in the first field, the form should look like this:
//Enter the number of inputs (1 is the start-value)
<input type="text" size="3" maxlength="3" id="count" name="count" value="1">
//Display that number of inputs (1 at start)
<input type="text" size="30" maxlength="30" id="input_1" name="input_1">
<input type="text" size="30" maxlength="30" id="input_2" name="input_2">
<input type="text" size="30" maxlength="30" id="input_3" name="input_3">
<input type="text" size="30" maxlength="30" id="input_4" name="input_4">
<input type="text" size="30" maxlength="30" id="input_5" name="input_5">
How can I make this? MUST I use js?
Here's a simple javascript snippet that doesn't make use of any frameworks:
function addInputs() {
var count = parseInt(document.getElementById("count").value);
for (var i = 2; i <= count; i++) {
document.getElementById('moreinputs').innerHTML += '<input type="text" name="input_' + i + '" id="input_' + i + '" />';
}
}
In this example you have to add a container (div) with id 'moreinputs'. However, when calling this function more than once, it will not work properly (e.g. it can only increase the number of input but not decrease)
Yes, either you use javascript, or you send the form to the server, where a new html page with all the inputs is generated (e.g. with PHP).
Yes you must use js to do it dynamically on the spot You have a jQuery tag so I will show an example in jQuery
This is not the best example but it works and it's a starting point
JS:
$(function(){
$('#master').on('change', function() {
var count = $(this).val();
$('#otherInputs').html('')
for( var i = 0; i < count; i++) {
$('#otherInputs').append(
$('<input>', {type: 'text'})
);
}
});
});
HTML:
<input type="number" id="master" value="1">
<div id="otherInputs"></div>
Demo
In English this is saying...
When you change #master I will empty #master (html('')) loop through and append a new input depending on #master's value
Here's the FIDDLE. Hope it helps. :)
html
<input type="text" size="3" maxlength="3" id="count" name="count" value="1">
<div id="container"></div>
script
$('#count').on('keyup', function () {
var $this = $(this);
var count = $this.val();
$('#container').empty();
for (var x = 1; x <= count; x++) {
var newInput = '<input type="text" size="30" maxlength="30" id="input_' + x + '" name="input_' + x + '">';
$('#container').append(newInput);
}
});
This worked for me
function AddField() {
var count = $("#countetfield").val();
var i = 1;
var id = $("#container .testClass:last").attr('name');
var test = id.split("_");
id_name = test[1];
while (i <= count) {
id_name++;
var a = '<input type="text" class="testClass" size="30" maxlength="30" id="input_' + id_name + '" name="input_' + id_name + '"/>';
$("#container").append(a);
i++;
}
}
<input type="text" id="countetfield" value="1" />
<input type="button" value="Go" onclick="AddField();" />
<div id="container">
<input type="text" class="testClass" size="30" maxlength="30" id="input_1" name="input_1" />
</div>

Categories

Resources