I am trying to create a number of text boxes with specific captions in front of each text box, dynamically.
I want the actual jquery code to create the textboxes and labels to lie within the following for loop---
function addelements(){
jQuery('<form action="test" id="data-form" name="data-form" method="POST" onsubmit="senddatafinal();"> <p> This is a new form </p><br />First name: <input type="text" name="firstname" /><br />Last name: <input type="text" name="lastname" />').appendTo('body');
for(i=0; i<=3; i++)
{
textmessage= "This is element # " + (i+1);
fieldname= "field_" + (i+1);
//now add code to show label stored in 'textmessage'
//to the form 'data-form'
//now add code to show text box with name stored in 'fieldname'
//to the form 'data-form'
}
}
You can always use a table to make it simple.
$('[id$=yourtable] > tbody:last').append('<input...>Label');
Found the below code (slightly modified it for my requirements) at http://www.mkyong.com/jquery/how-to-add-remove-textbox-dynamically-with-jquery/
Code----
<script type="text/javascript">
$(document).ready(function(){
var counter = 1;
$("#addButton").click(function () {
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Textbox #'+ counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
});
</script>
Related
I am trying to create multiple fields when I enter a number to tell it how many to create... I have utilised some code that I have written previously but now it's no longer working.
HTML:
<input type="text" name="rows">
jQuery:
$(document).ready(function() {
$('#rows').change(function() {
var rows = $(this).val();
for(i=0;i<=rows;i++) {
$('#form').append('<div><input type="text" name="N' + i + '"></div>');
$('#form').append('<div><select name="S'+ i +'"><option value="Text">Text</option><option value="editor">Editor</option></select></div>');
$('#form').append('<div><input type="text" name="V' + i + '"></div>');
}
}
}
Fiddle: https://jsfiddle.net/dc5665xk/1/
ID attribute is missing for rows element.
There is no form element having form as ID
Syntax error as closing braces were missing.
Note: var keyword was missing in for-loop
$(document).ready(function() {
$('#rows').change(function() {
var rows = $(this).val();
for (var i = 0; i <= rows; i++) {
$('#form').append('<div><input type="text" name="N' + i + '"></div>');
$('#form').append('<div><select name="S' + i + '"><option value="Text">Text</option><option value="editor">Editor</option></select></div>');
$('#form').append('<div><input type="text" name="V' + i + '"></div>');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form id="form">
<input type="text" name="rows" id="rows">
</form>
So this is what the page looks like currently:
The first one is hardcoded in and then the rest are added/removed by the buttons. The first one can also be added and removed from the buttons. I want to call a jquery function when the dropdown is changed to change the type from textbox/radiobutton (and text)/checkbox (and text) etc.
Currently it only works on the first Question/Answer and only works if it is the original and not dynamically created. I'm not sure why that is.
Here is how the Q/A's are created and removed
$("#addButton").click(function () {
if (counter > max_fields) {
alert("Only " + max_fields + " Questions allowed");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Question #' + counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="questionbox' + counter + '" value="" />' +
' <select id="choice'+ counter +'"><option>Type</option><option>Radio Button</option><option>Text Box</option><option>Check Box</option></select>' +
'<button id = "remove' + counter + '">Remove</button>' +
'<br/><label>Answer #' + counter + ' : </label>' +
'<div id="Answers' + counter + '">' +
'Option 1: <input type="text" id="answerbox' + counter +
'1" name="answerbox' + counter + '" value="" />' +
'<br/>Option 2: <input type="text" id="answerbox' + counter +
'2" name="answerbox' + counter + '" value="" />' +
'<br/>Option 3: <input type="text" id="answerbox' + counter +
'3" name="answerbox' + counter + '" value="" />' +
'<br/>Option 4: <input type="text" id="answerbox' + counter +
'4" name="answerbox' + counter + '" value="" /></div>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if (counter == 1) {
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
This is how I tried to get it to change types
$('#choice1').change(function () {
var selected_item = $(this).val()
var searchEles = document.getElementById("Answers1").children;
alert(searchEles.length);
for(var i = 0; i < searchEles.length; i++) {
$('#answerbox1' + i).attr('type', selected_item);
//alert(searchEles.length);
}
});
The web page code is as follows
<input type='button' value='Add Question' id='addButton'/>
<input type='button' value='Remove Question' id='removeButton'/>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Question #1 : </label>
<input type='text' id='questionbox1'/>
<select id="choice1" onchange="$('#choice').val('id');"> //this on change was added and currently does nothing it seems.
<option value="">Type</option>
<option value="radio">Radio Button</option>
<option value="text">Text Box</option>
<option value="checkbox">Check Box</option>
</select>
<button id="remove1">Remove</button>
<br/><label>Answer #1 : </label>
<div id="Answers1">
Option 1: <input type="text" id='answerbox11' name='answerbox1' value="" />
<br/>Option 2: <input type="text" id='answerbox12' name='answerbox1' value="" />
<br/>Option 3: <input type="text" id='answerbox13' name='answerbox1' value="" />
<br/>Option 4: <input type="text" id='answerbox14' name='answerbox1' value="" />
</div>
</div>
</div>
I tried to do something like onchange and then get the ID and go from there but that didn't work. I know it doesn't match the back end jquery name.
TL;DR
I don't know how to dynamically write the jQuery function to work
for all of them.
I don't know why even if I hardcode it to #choice1 it will work
when its first created but not if i remove and add it even though it
has the same exact values. I think it might MAYBE have to do with
for loop, because the alert doesn't even trigger the second time
around.
You could try
$(document).on("change", ".selector", function(){
//do something
});
//Edit
Add to the select element class for example select-option and a tag that will hold the select's counter
//JS
...'<select id="choice'+counter+'" class="select-option" number="'+counter+'">'...
and then your on change function would look something like
$(document).on("change", ".select-option", function(){
//do something
var selected_type = $(this).attr('value');
var ans_number = $(this).attr('number');
$("#answerbox"+ans_number).children('input').attr('type', selected_type);
});
I hope this will help :)
For dynamically added elements use
$(selector).on("change", callback)
If element is dynamic then Jquery will not bind directly as
$('#choice1').change(function (){});
But for that you need to call same function with some static element.
For Ex:
$(".listingDiv").find('#choice1').change(function (){});
or
$(document).find('#choice1').change(function (){});
and it will work. try it.
When elements will be aded dynamically, best practice is to delegate the handler(s). Put your handler on the containing div or window/document
.
First
<select id="choice1" onchange="$('#choice').val('id');"> //this on change was added and currently does nothing it seems.
This is one reason your never be called. If you bind an event listener to an element, you should not write the actual JS code inside the element.
Second
Bind your listener like this:
$('#choice1').on("change", function () {
var selected_item = $(this).val()
var searchEles = document.getElementById("Answers1").children;
alert(searchEles.length);
for(var i = 0; i < searchEles.length; i++) {
$('#answerbox1' + i).attr('type', selected_item);
//alert(searchEles.length);
}
});
i'm trying to populate div with select option but i don't really now where to start...
i have some code to live edit the "title" of the div, but now i want to add to a specific div his option...
Here's the code that i have for now:
var rooms = $("#howmanyrooms").val();
var roomcounter = 1;
$(".design-your-system-page-playground-container").show();
for (var i = 0; i < rooms; i++) {
// $("<div class='appendeddiv'>Room-" + roomcounter++ + "</div>").appendTo(".housecontainer");
// $("<span>Room-" + roomcounter + " name</span> <input type='text' placeholder='name' id='room-" + roomcounter + "-id'></div></br>").appendTo(".infoncontainer");
//
$("<div class='design-your-system-page-rooms targetDiv_" + roomcounter + "'>Room-" + roomcounter + "</div>").appendTo(".design-your-system-page-house");
$("<span>Room-" + roomcounter + " name</span> <input type='text' placeholder='name' id='room-" + roomcounter + "-id' class='textInput' lang='targetText_" + roomcounter + "'> <select>Heating<option value='radiator'>Radiator</option><option value='underfloor'>Underfloor</option><option value='electric'>Electric</option></select> <select class='design-your-system-number-of-radiator-select'><option value='0'>0</option><option value='1'>1</option><option value='2'>2</option><option value='3'>3</option><option value='4'>4</option><option value='5'>5</option><option value='6'>6</option><option value='7'>7</option><option value='8'>8</option><option value='9'>9</option></select> <span>Do you want the room to be smart (footprint) ?<input type='radio' name='smart-yes' value='smart-yes'>Yes</input> <input type='radio' name='smart-no' value='smart-no'>No</input></div></br>").appendTo(".design-your-system-page-edit-room-container");
roomcounter++;
};
if ($('.design-your-system-page-house').find('.design-your-system-page-rooms').length) {
$("#buttonaddrooms").hide();
}
$("input.textInput").on("keyup", function () {
var target = $(this).attr("lang").replace("Text", "Div");
$("." + target).text($(this).val());
});
as you can see, when i click the button, i'll append to the parent as many child divs as the value typed into the textbox and i also create the same number of "row" containing the name and other option (two select and a radio)
i'm already able to live edit the name of the ralative div, but now i want to add to that div also the other options
here a jsfiddle to help you understand what i have and what i want:
http://jsfiddle.net/3cyST/
if is not clear please tell me.
thanks
please check this fiddle:
i made your target variable global to be reusable, i also added a class for your first select element which is selecting
ive updated it and it now appends the value of your test onchange using:
$("select.selecting").on("change", function () {
$("." + target).append($(this).val());
});
you can work for the rest now.
EDIT(for the question of OP on the comment) :
to get value of radio button i'll give you 2 ways :
in Javascript :
if (document.getElementById('ID_OF_RADIO').checked) {
rate_value = document.getElementById('ID_OF_RADIO').value;
}
in jQuery :
$("input[name=RADIO_NAME]:checked").val();
give the select an id, then use
$("#id").on("change",function(){
console.log(this.value);
//whatever you want to do with the value
})
...same for the radio buttons and other options...also note that the radio buttons shouldn't have different names:
<input type='radio' name='radio_{put id here}' value='yes'>Yes</input>
<input type='radio' name='radio_{put id here}' value='no'>No</input>
another thing for the readabillity of the code: try using a template....just put a <noscript> with an id in the code...use some distinctive syntax to put placeholders in it, and replace them at runtime:
HTML:
<noscript id="template">
RoomName: <input type="text" id="roomName_%ROOMID%" />
Do you want...
<input type='radio' name='radio_%ROOMID%' value='yes'>Yes</input>
<input type='radio' name='radio_%ROOMID%' value='no'>No</input>
</noscript>
JS:
for (var i = 0; i < rooms; i++) {
var tplcode = $("#template").html();
tplcode = tplcode.replaceAll("%ROOMID%",roomcounter);
$($.pareHTML(tplcode)).appendTo(".design-your-system-page-edit-room-container");
$("input[name='radio_"+roomcounter+"']").on("change",function(){
console.log("user wants:" + $("input[name='radio_"+roomcounter+"'][checked]").val())
});
roomcounter++;
}
// these functions help replacing multiple occurances
String.prototype.replaceAll = function(find,replace){
return this.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}
//escapse all regEx chars, so the string may be used in a regEx
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
Fiddle: http://jsfiddle.net/3cyST/4/
I have a function to add and remove a field but the remove function doesnt work somehow.
HTML:
<div id="parts">
Part
<input type="text" id="auto_part" name="auto_part" />
<br />
Description
<input type="text" id="auto_description" name="auto_description" />
<br />
</div>
Add another part
jQuery:
$(function() {
var scntDiv = $('#parts');
var i = $('#parts input').size();
$('#addField').on('click', function() {
$('<br /><div id="parts"><span>Part</span> <input type="text" id="auto_part'+i+'" name="auto_part'+i+'" /><br />').appendTo(scntDiv);
$('<span>Description</span> <input type="text" id="auto_description'+i+'" name="auto_description'+i+'" /> <br />').appendTo(scntDiv);
$('<input type="hidden" id="row_count" name="row_count" value="" />').appendTo(scntDiv);
$('Remove</div>').appendTo(scntDiv);
i++;
return false;
});
$('#removefield').on('click', function() {
if( i > 2 ) {
$(this).parents('div').remove();
i--;
}
return false;
});
});
The problem must have to do with this line:
$('#removefield').on('click', function() {
It doesnt pass that condition.
When I click on Remove it doesnt do anything at all it just scrolls to the top.
You are binding the click handler to the elements that are present in the DOM. But, your #removefield element is being dynamically added. So, the event handler is not attached to it.
You can use .on() to use event delegation and handle also future elements. Also, you may want to use classnames instead of and id attributes. id attributes need to be unique, but you can set the classname to as many elements as you want.
Remove
$("#parts").on("click", ".removefield", function() {
/* ... */
});
The reason why your "Remove" link doesn't work is because you are adding the dynamic <div> element by parts hence making it invalid markup. You should be adding it all together at once. For example,
$('#addField').on('click', function () {
var part = '<div id="parts' + i + '"><span>Part</span> <input type="text" id="auto_part' + i + '" name="auto_part' + i + '" /><br/>' +
'<span>Description</span> <input type="text" id="auto_description' + i + '" name="auto_description' + i + '" /> <br />' +
'<input type="hidden" id="row_count' + i + '" name="row_count' + i + '" value="" />' +
'Remove</div>';
scntDiv.after(part);
i++;
return false;
});
$(document).on("click", ".removefield", function() {
if( i > 2 ) {
$(this).parent('div').remove();
i--;
}
return false;
});
You can see it here.
try
$('#removefield').live("click", function() {
I am trying to add extra input fields but this code works with jquery 1.3 once i try with jquery 1.7. It doesn't work
var newTr = $(document.createElement('tr'))
.attr("id", 'line' + counter);
newTr.after().html('<td><input type="text" name="name' + counter +
'" id="name' + counter + '" value="" style="width:100px;"></td><td><input type="text" name="phone' + counter +
'" id="phone' + counter + '" value="" style="width:100px;"></td>');
newTr.appendTo("#dyTable");
I guess there is problem with newTr.after().html() and newTr.appendTo("#dyTable"); Please help me
document.createElement('tr') is not needed and you can simply use $('<tr></tr>') to create new element. This should work,
var newTr = $('<tr></tr>').attr("id", 'line' + counter);
For adding <td> content, change, newTr.after().html('...') to newTr.html('...'). I don't think after is required.