How to duplicate specific sections of form? - javascript

I have some code as the following example:
<form>
<label>name</label><input type="text" />
<label>phone</label><input type="text" />
<label>color</label><select>
<option>red</option>
<option>blue</option>
<option>green</option>
</select>
<label>e-mail</label><input type="text" />
</form>
And I want to duplicate only the select section if the user needs it via button between the select section and the e-mail input field.
I'm not really into JavaScript or jQuery so it would very appreciated if you could also add a clear explanation to your answer.

You can use JQuery clone function to clone your element and then append it where you need it, or if you need to have a different id for each section you need you might want to save an index and set it as an id each time you add a section
var index = 1;
function addColor() {
var nextSection = '<div id="color-section-' + index++ + '">' +
'<label>color</label>' +
'<select>' +
'<option>red</option>' +
'<option>blue</option>' +
'<option>green</option>' +
'</select><br />' +
'</div>';
$(nextSection).appendTo($("#color-section"));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="my-form">
<label>name</label><input type="text" /><br />
<label>phone</label><input type="text" /><br />
<div id="color-section">
<label>color</label>
<select>
<option>red</option>
<option>blue</option>
<option>green</option>
</select><br />
</div>
<label>e-mail</label><input type="text" /><br />
</form>
<button onClick="addColor()">Add Color</button><br />

You can use clone() to copy an element. See below example with an explanation.
A div element with name "color-selections" contain a initial select tag.
<div class="color-selections">
<select>
<option>red</option>
<option>blue</option>
<option>green</option>
</select>
</div>
There will be unknown number of select tag inside the "color-selections" class. So i use first() method to get first element (Original select tag).
$(".color-selections select:first")
Copy the first element using clone().
$(".color-selections select:first").clone()
Finally, Append this clone element into "color-selections" class using appendTo() method.
$(".color-selections select").first().clone().appendTo(".color-selections");
function addColor() {
$(".color-selections select:first").clone().appendTo(".color-selections")
//OR $(".color-selections select").first().clone().appendTo(".color-selections");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<label>name</label><input type="text" />
<label>phone</label><input type="text" />
<label>color</label>
<div class="color-selections">
<select> //$(".color-selections select:first")
<option>red</option>
<option>blue</option>
<option>green</option>
</select>
</div>
<input type="button" value="+" onclick="addColor();">
<label>e-mail</label><input type="text" />
</form>
I hope design is not an important part of sample code.

Related

How Embed a HTML form with additional element on condition using JavaScript

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>form</title>
<link href="MyStyle.css" rel="stylesheet" type="text/css">
</head>
<body class="form">
<h1>Application Form</h1>
<form class="fdmain" method="post" id="form2" name="form2" action=>
<p>
<label for="textfield">Name:</label>
<input type="text" name="stdname" id="tfname">
</p>
<p>Father Name:
<input type="text" name="fname" id="tffathername">
</p>
<p>
<label for="email">Email:</label>
<input type="email" name="email" id="email">
</p>
<p>
<label for="tel">Tel:</label>
<input type="tel" name="tel" id="tel">
</p>
<p>Select Application Type:
<select name="appselect" id="appselect" onchange="myfunc()">
<option value="" selected>Select Here </option>
<option value="Course_Application">Course Application</option>
<option value="Acc_State">Statement of Account</option>
<option value="Invite">Invitation</option>
<option value="Complain_Application">Complain</option>
<option value="SA_Applications">Student Affair Application</option>
</select>
</p>
<script type="application/javascript">
function myfunc(){
var Appread = document.forms[0].appselect.value;
if(Appread.localeCompare("Course_Application")==0)
{
document.write( "<p>");
document.write("<label>");
document.write("<input type='radio' class='CARadio' name='CAType' value='drop' id='CAType_0'>");
document.write("Drop</label>");
document.write("<br>");
document.write("<label>");
document.write("<input type='radio' class='CARadio' name='CAType' value='withdraw' id='CAType_1'>");
document.write("Withdraw</label>");
document.write("<br>");
document.write("<label>");
document.write("<input type='radio' class='CARadio' name='CAType' value='other' id='CAType_2'>");
document.write("Other</label>");
document.write("<br>");
document.write("</p>");
document.write("</p>");
document.write("<p>If Other Please Specify:</p>");
document.write("<p>");
document.write("<textarea name='txfdCApp' id='txtCAP'></textarea>");
document.write("</p>");
}
}
</script>
<p>Application Details:</p>
<p>
<textarea name="textarea" id="textarea" rows="10" cols="30" ></textarea>
</p>
<p>
<input name="submit" type="submit" id="submit2" formmethod="POST" value="Submit">
</p>
<p> </p>
</form>
</body>
</html>
I have only made the code for the first selection option. But the part of the code I have written in myfunc opens in another window. I want to code in a way that for every particular option the additional code opens on the same form after the end of select tag and before the additional information tag.
What am I doing wrong.
I would to suggest to place all your conditionally required fields into a div. Then use JavaScript to determine whether to show the div or not. This eliminates the needs to create HTML nodes manually, which can be messy.
You also need to consider the implications if the user picks the same option in the select list multiple times... it will keep adding nodes, which is bad.
Relevant code snippet:
<div id='extra_questions' style='display: none; background-color: #0094ff;'>
<!-- add radio buttons or whatever here -->
Question #1<br />
Question #2<br />
Etc.<br />
</div>
<script type="application/javascript">
function myfunc() {
var Appread = document.forms[0].appselect.value;
if (Appread.localeCompare("Course_Application") == 0) {
document.getElementById('extra_questions').style.display = 'block';
} else {
document.getElementById('extra_questions').style.display = 'none';
}
}
</script>
You are doing it backwards. :-)
You are writing code with document.write. Where do you think this code goes to?
(Remember that the javascript is executed when an option changes in your SELECT.)
End of document? (Which already had its tags I presume)
The right way to add "live" elements to your page is by creating new DOM elements.
It might seem daunting in the beginning, but give it a shot.
I recommend starting here (and avoid w3schools):
https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement
Try this.
After the </select> tag, add this.
<option value="SA_Applications">Student Affair Application</option>
</select>
</p>
<div id="ApplicationTypeResult"></div>
Then, save this as testresult.html in the same folder.
<p><label><input type='radio' class='CARadio' name='CAType' value='drop' id='CAType_0'>Drop</label><br>
<label><input type='radio' class='CARadio' name='CAType' value='withdraw' id='CAType_1'>Withdraw</label><br>
<label><input type='radio' class='CARadio' name='CAType'>Other</label><br></p>
<p>If Other Please Specify:</p>
<p><textarea name='txfdCApp' id='txtCAP'></textarea></p>
And try this.
function myfunc() {
var Appread = document.forms[0].appselect.value;
if(Appread.localeCompare("Course_Application")==0) {
document.getElementById("ApplicationTypeResult").innerHTML = '<object type="text/html" data="testresult.html"></object>';
}
It will be easier if you use jquery by
function myfunc() {
var Appread = document.forms[0].appselect.value;
if(Appread.localeCompare("Course_Application")==0) {
$("#ApplicationTypeResult").load("testresult.html");
}
Hope this helps, please change your div id name to whatever you might need and note the pathname to whereever you might save the file.
Expected behaviour will be this, (just plain).

Create elements based on checkbox selection

I have this HTML:
<fieldset style="" title="Variaciones" id="product-create-step-3" class="fstep">
<legend>Variaciones</legend>
<section id="choices">
<input type="checkbox" value="24" id="24" name="Size"> Size
<input type="checkbox" value="25" id="25" name="Color"> Color
<section style="display: none" class="options_holder"></section>
<section style="display: none" class="variations_holder"></section></section>
</fieldset>
I need to create some input based on what checkbox/es was marked. For example if I mark first one 'Size' I should obtain this:
<section style="display: none" class="options_holder">
<input name="size[24][]" value="" placeholder="Write your size" />
</section>
if I mark second one 'Color' I should obtain this:
<section style="display: none" class="options_holder">
<input name="color[25][]" value="" placeholder="Write your color" />
</section>
if I mark both 'Size' & 'Color' I should obtain this:
<section style="display: none" class="options_holder">
<input name="size[24][]" value="" placeholder="Write your size" />
<input name="color[25][]" value="" placeholder="Write your color" />
</section>
How I would do that?
UPDATE 1
I'm trying to get which checkbox was checked by doing this:
$("#choices :checked").each(function() {
console.log(this.id + "was checked");
});
But it's not working
UPDATE 2
I realize into another problem, how I check when a checkbox was checked and after trigger some code without know any data of the checkbox? I have a code that generates check-boxes on the fly so I'll never know their name's or id's or any other data. My template for that creation looks like this:
<input type="checkbox" name="{{ entity.getLabel|lower }}" id="{{ entity.getLabel|lower ~ "_choice" }}" value="{{ entity.getId }}" /> {{ entity.getLabel }}
Where for example name could take "color" and in that case id will be "color_choice" or name could take "size" and in that case id will be "size_choice", sometimes one is created some time both are created. What I need to know and I don't is how to know which check-box was checked and when trigger some event as for example create some others input's on the fly. How do I deal with this part too?
So, your javascript should work if you change your selector to include the element that uses the pseudo-selector:
$("#choices input:checked").each(function() {
console.log(this.id + "was checked");
});
As for accessing the attribute values, you can use either the native javascript object that you're using, i.e.:
console.log("value is " + this.value);
Or you can use jQuery's attr()
console.log("name is " + $(this).attr('name'))
A working example showing both cases, as well as having attached the event to any click of input items is at this jsfiddle:
http://jsfiddle.net/k3B73/
<fieldset style="" title="Variaciones" id="product-create-step-3" class="fstep">
<legend>Variaciones</legend>
<section>
<input type="checkbox" value="24" id="24" name="Size" id='size_choice'> Size
<input type="checkbox" value="25" id="25" name="Color" id='color_choice'> Color
<section style="display: none" class="options_holder" id='options_holder'></section>
<section style="display: none" class="variations_holder"></section>
</section>
</fieldset>
<script type="text/javascript">
$(document).ready(function(){
$('#size_choice').click(function(){
if ($(this).is(':checked'))
$("#options_holder").append('<input name="size[24][]" value="" placeholder="Write your size" id="size" />');
else
$("#size").destroy();
});
$('#color_choice').click(function(){
if ($(this).is(':checked'))
$("#options_holder").append('<input name="color[25][]" value="" placeholder="Write your color" id="choice" />');
else
$("#color").destroy();
});
})
</script>

Constructing an array of objects

I need to submit a Collection (set, list, array) with objects that consists of:
id, phoneNumber, phoneType
I have a bunch of divs, here's some example HTML:
<div id="f9" class="facilityBox">
<div style="float:left;">
<label>BRANCH</label>
</div>
<div style="float:right;"> Save changes
</div>
<div class="phoneSet">
<input type="text" value="787-788-1111" class="phones" name="number" />
<select class="phoneType" name="type">
<option selected="selected" value="PHONE">Phone</option>
<option value="FAX">Fax</option>
</select>
<input type="hidden" value="6" class="phoneId" name="id" />
</div>
<div class="phoneSet">
<input type="text" value="787-795-4095" class="phones" name="number" />
<select class="phoneType" name="type">
<option value="PHONE">Phone</option>
<option selected="selected" value="FAX">Fax</option>
</select>
<input type="hidden" value="106" class="phoneId" name="id" />
</div>
</div>
This div's id will be f+identifier, so for now it's f9
the js I have so far is:
Location.submitUpdateFacility = function (facilityId) {
$("#updateFacility input[name=index]").val(facilityId);
var id = facilityId;
var phones;
$("#" + id + " .phoneSet").each(function () {
phones += {
id: $(".phoneId input[name=id]").val(),
phoneNumber: $(".phones input[name=number]").val(),
phoneType: $(".phoneType select[name=type]").selected().val()
};
});
};
My problem is upon Firebug/Chrome console debugging, it does not go into the loop and thus no array is ever created. What am I doing wrong?
The problem looks to be that you are passing "9" in as the function parameter that is then being converted to a jquery selector as "#" + id + " .phoneSet". This is generating "#9 .phoneSet" which is incorrect.
You should be using "#f" + id + " .phoneSet".
It should also be noted that the other selectors that you use (eg ".phoneId input[name=id]") may also need correcting before this works fully as you expect.

javascript form option value split into two different input values

Okay so I have been trying to figure this out but do not have the knowledge to proceed.
I have a form with select options. The options will have two values, input-value="value1/value2".
I have a script started that pulls out the value and creates an array. I need ti figure out how to separate the two values and print out into two separate input values.
<html>
<body>
<p>The Thank you page is <b id='brochure'>is what?</b> </p>
<p>This should print out the selected fid <script>document.getElementById('brochure').innerHTML = '<input id="" value="'+option_array[1]+'" />';</script></p>
<form>
Activity Level: <select id="activity_level">
<option value="null">Please Choose One...</option>
<option id="brochure" value="brochure/print">fid/sid</option>
<option id="online" value="online/web">Three/Four</option>
<option id="inPerson" value="inPerson">Five/Six</option>
</select></br>
<input type='button' onclick='brochure_select()' value='Change Text'/>
<script type="text/javascript">
function brochure_select() {
var option_result = document.getElementById("activity_level").value;
var option_array=option_result.split("/");
document.getElementById('brochure').innerHTML = option_array[1];
}
</script>
// below is where I want to two value to show up.
<input type="hidden" name="fid" value="brochure" />
<input type="hidden" name="sid" value="print" />
</form>
</body>
</html>
I have tried the split function but I am not sure how to get it into the different input values.
Any ideas that I can research or code examples someone might have to share. I have gone through many different searches and have not found what I am looking for...
Thanks
Tim
What you need is an id attribute for your hidden input elements, and to use the value property instead of innerHTML.
<form>
Activity Level:
<select id="activity_level">
<option value="null">Please Choose One...</option>
<option id="brochure" value="brochure/print">fid/sid</option>
<option id="online" value="online/web">Three/Four</option>
<option id="inPerson" value="inPerson">Five/Six</option>
</select><br />
<input type='button' onclick='brochure_select()' value='Change Text'/>
</form>
<input type="hidden" id="fid" name="fid" value="" />
<input type="hidden" id="sid" name="sid" value="" />
<script>
function brochure_select() {
var option_result = document.getElementById("activity_level").value;
var option_array=option_result.split("/");
document.getElementById('fid').value = option_array[0];
document.getElementById('sid').value = option_array[1];
}
</script>

Find ID of a selectmenu

How can I get the name of the select tag?
I have several select menus. I can retrieve the submitted options. However, I would like to get the name, or even better, the ID of the select tag that holds the options.
Sample HTML:
<div id="prodAttributes_2">
<form id="attributesubmit">
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<div role="heading" >Options:</div>
<select name="Memory" id="4">
<option value="3">16 mb</option>
<option value="4">32 mb</option>
</select>
<select name="Model" id="3">
<option value="6">Premium</option>
<option value="7">Deluxe</option>
</select>
</fieldset>
</div>
<input type="button" id="submitme" value="send" />
</form>
</div>
Solved Fiddle: JSFiddle
Add
var name = $(this).attr("name");
to your $('select').each call: http://jsfiddle.net/xPGUE/
You can use this.id within the each().
Note you can get the name with $(this).attr('name')
I've forked your jsfiddle
in your fiddle, where you get the alert
alert('Value: ' + selectedOption.val() + ' Text: ' + selectedOption.text());
you can access to the name or id of the option using
selectedOption.attr('name')
selectedOption.attr('id')
Try this:
$('select').each(function() {
alert($(this).attr('name'));
});

Categories

Resources