php javascript - add remove dynamic form (with datepicker input) - javascript

i use some code to clone form elements but i dont know how it works with with datepicker.
Can someone update the code that i can use datepicker by input what can be clone? With query ui?
//define template
var template = $('#sections .section:first').clone();
//define counter
var sectionsCount = 1;
//add new section
$('body').on('click', '.addsection', function() {
//increment
sectionsCount++;
//loop through each input
var section = template.clone().find(':input').each(function(){
//set id to store the updated section number
var newId = this.id + sectionsCount;
//update for label
$(this).prev().attr('for', newId);
//update id
this.id = newId;
}).end()
//inject new section
.appendTo('#sections');
return false;
});
//remove section
$('#sections').on('click', '.remove', function() {
//fade out section
$(this).parent().fadeOut(300, function(){
//remove parent element (main section)
$(this).parent().parent().empty();
return false;
});
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sections">
<div class="section">
<fieldset>
<legend>test form - <a href="#" class='button red remove'>delete</a></legend>
<p>
<label for="number1">number1:</label>
<input type="text" name="number1[]"/>
</p>
<p>
<label for="number2">number2:</label>
<input type="text" name="number2[]"/>
</p>
<p>
<label for="selcet1">selcet1:</label>
<select name="select1[]" required>
<option value="1" >1</option>
<option value="2" >2</option>
</select>
</p>
<p>
<label for="selcet2">selcet2:</label>
<select name="selcet2[]" required>
<option value="1" >1</option>
<option value="2" >2</option>
</select>
</p>
<p>
<label for="date">Date:</label>
<input type="text" name="date[]" required />
</p>
<p>
<label for="text">text:</label>
<textarea rows=3 type="text" name="text[]" > </textarea>
</p>
</fieldset>
</div>
</div>
<a href="#" class='addsection'>add form</a>
I dont know how to add a datepicker by the
// input type="text" name="date[]" required // that i can clone and use.
Please can someone help me that it works?

JqueryUI solution
//define template
var template = $('#sections .section:first').clone();
//define counter
var sectionsCount = 1;
//add new section
$('body').on('click', '.addsection', function() {
//increment
sectionsCount++;
//loop through each input
var section = template.clone().find(':input').each(function(){
//set id to store the updated section number
var newId = this.id + sectionsCount;
//update for label
$(this).prev().attr('for', newId);
//update id - THIS CAUSES JqueryUI Datepicker to bug, also you shouldn't use numerical only IDs
//this.id = newId;
}).end()
//inject new section
.appendTo('#sections');
//initialize datePicker on last name=date[] element in HTML DOM
$("input[name='date[]']").last().datepicker();
return false;
});
//init original datePicker in HTML DOM
$("input[name='date[]']").last().datepicker();
//remove section
$('#sections').on('click', '.remove', function() {
//fade out section
$(this).parent().fadeOut(300, function(){
//remove parent element (main section)
$(this).parent().parent().empty();
return false;
});
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css">
<div id="sections">
<div class="section">
<fieldset>
<legend>test form - <a href="#" class='button red remove'>delete</a></legend>
<p>
<label for="number1">number1:</label>
<input type="text" name="number1[]"/>
</p>
<p>
<label for="number2">number2:</label>
<input type="text" name="number2[]"/>
</p>
<p>
<label for="selcet1">selcet1:</label>
<select name="select1[]" required>
<option value="1" >1</option>
<option value="2" >2</option>
</select>
</p>
<p>
<label for="selcet2">selcet2:</label>
<select name="selcet2[]" required>
<option value="1" >1</option>
<option value="2" >2</option>
</select>
</p>
<p>
<label for="date">Date:</label>
<input type="text" name="date[]" required />
</p>
<p>
<label for="text">text:</label>
<textarea rows=3 type="text" name="text[]" > </textarea>
</p>
</fieldset>
</div>
</div>
<a href="#" class='addsection'>add form</a>

HTML5 DatePicker Solution
Native HTML5 datepicker is supported only in modern browsers and not even all of them.
Simply use type="date" instead of type="text"
If you want 100% working datepicker, you will have to look at JqueryUI.
If you want JqueryUI datepicker to work with cloned elements, you will have to initialize new date input fields as datepicker jquery input element after cloning them.
//define template
var template = $('#sections .section:first').clone();
//define counter
var sectionsCount = 1;
//add new section
$('body').on('click', '.addsection', function() {
//increment
sectionsCount++;
//loop through each input
var section = template.clone().find(':input').each(function(){
//set id to store the updated section number
var newId = this.id + sectionsCount;
//update for label
$(this).prev().attr('for', newId);
//update id
this.id = newId;
}).end()
//inject new section
.appendTo('#sections');
return false;
});
//remove section
$('#sections').on('click', '.remove', function() {
//fade out section
$(this).parent().fadeOut(300, function(){
//remove parent element (main section)
$(this).parent().parent().empty();
return false;
});
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sections">
<div class="section">
<fieldset>
<legend>test form - <a href="#" class='button red remove'>delete</a></legend>
<p>
<label for="number1">number1:</label>
<input type="text" name="number1[]"/>
</p>
<p>
<label for="number2">number2:</label>
<input type="text" name="number2[]"/>
</p>
<p>
<label for="selcet1">selcet1:</label>
<select name="select1[]" required>
<option value="1" >1</option>
<option value="2" >2</option>
</select>
</p>
<p>
<label for="selcet2">selcet2:</label>
<select name="selcet2[]" required>
<option value="1" >1</option>
<option value="2" >2</option>
</select>
</p>
<p>
<label for="date">Date:</label>
<input type="date" name="date[]" required />
</p>
<p>
<label for="text">text:</label>
<textarea rows=3 type="text" name="text[]" > </textarea>
</p>
</fieldset>
</div>
</div>
<a href="#" class='addsection'>add form</a>

Related

Is it possible to dynamically change the color of a dropdown or change list item color when a radio option is selected in Javascript/JQuery?

I have code that allows me to select a radio option, say, 'Work', and have the dropdown box automatically select 'Work' in response. But is it possible to go further and to select the radio option 'Work', and have the 'Work' dropdown be selected and also change to blue, for instance. And green for 'Grocery', red for 'Chores', etc. Maybe even go further than that and have the subsequent task list items also color-coded based on Category?
//task entry interface is dynamically changed based on type of task entered
//dynamic list
$(document).ready(function ($) {
$(document).on('change', 'input[name="category"]', function () {
var lookup_val = $(this).val();
$("#mySelect option").filter(function () {
return $(this).val() === lookup_val;
}).first().prop('selected', true).siblings().prop('selected', false);
$("select[name='mySelect']").trigger({ type:'change', originalEvent:'custom' });
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="list-wrap" contenteditable="false">
<div class="list-inner-wrap">
<h2 class="title">ToDo List</h2>
<h3 class="title">Add Task</h2>
<!--<h4>Task Name</h4>-->
<form method="POST" action="..." name="radiodemo" id="radiodemo" onsubmit="getCategory();">
<label for="category"> Category:</label>
<input type="radio" id="grocery" name="category" value="Grocery" class="category" checked="checked">
<label for="grocery">Grocery</label>
<input type="radio" id="work" name="category" value="Work" class="category">
<label for="work">Work</label>
<input type="radio" id="chores" name="category" value="Chores" class="category">
<label for="chores">Chores</label>
<input type="radio" id="finance" name="category" value="Finance" class="category">
<label for="finance">Finance</label>
<br>
<!--dynamic radio option -->
Select your category:
<select id="mySelect">
<option value="Groceries">Groceries</option>
<option value="Work">Work</option>
<option value="Chores">Chores</option>
<option value="Finance">Finance</option>
</select>
<br><br>
</form>
<p id="demo"></p>
Yes is possible :)
I add an if for every choise and add class and remove other.
//task entry interface is dynamically changed based on type of task entered
//dynamic list
$(document).ready(function ($) {
$(document).on('change', 'input[name="category"]', function () {
var lookup_val = $(this).val();
$("#mySelect option").filter(function () {
return $(this).val() === lookup_val;
}).first().prop('selected', true).siblings().prop('selected', false);
$("select[name='mySelect']").trigger({ type:'change', originalEvent:'custom' });
$( "#mySelect" ).removeClass();
if(lookup_val === 'Groceries'){
$( "#mySelect" ).addClass( "red" );
}else if(lookup_val === 'Work'){
$( "#mySelect" ).addClass( "blue" );
}else if(lookup_val === 'Chores'){
$( "#mySelect" ).addClass( "green" );
}else if(lookup_val === 'Finance'){
$( "#mySelect" ).addClass( "yellow" );
}
});
});
.red{
background-color:red;
color:white;
}
.blue{
background-color:blue;
color:white;
}
.green{
background-color:green;
color:white;
}
.yellow{
background-color:yellow;
color:white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="list-wrap" contenteditable="false">
<div class="list-inner-wrap">
<h2 class="title">ToDo List</h2>
<h3 class="title">Add Task</h2>
<!--<h4>Task Name</h4>-->
<form method="POST" action="..." name="radiodemo" id="radiodemo" onsubmit="getCategory();">
<label for="category"> Category:</label>
<input type="radio" id="grocery" name="category" value="Grocery" class="category" checked="checked">
<label for="grocery">Grocery</label>
<input type="radio" id="work" name="category" value="Work" class="category">
<label for="work">Work</label>
<input type="radio" id="chores" name="category" value="Chores" class="category">
<label for="chores">Chores</label>
<input type="radio" id="finance" name="category" value="Finance" class="category">
<label for="finance">Finance</label>
<br>
<!--dynamic radio option -->
Select your category:
<select id="mySelect" class='red'>
<option value="Groceries">Groceries</option>
<option value="Work">Work</option>
<option value="Chores">Chores</option>
<option value="Finance">Finance</option>
</select>
<br><br>
</form>
<p id="demo"></p>

change radio button checked attribute on basis of label html using jquery

I have a select drop down and if the onchange of select drop-down the option is yes than all the radio buttons should change to yes
<select class="is_poly_cover">
<option>No</option>
<option>Yes</option>
</select>
<input type="radio" name="v1" class=" additional_option_type_7" checked="checked" value="251">
<label class="" for="251">YES</label>
<input type="radio" name="v1" class=" additional_option_type_7" value="254">
<label class="" for="254">NO</label>
<input type="radio" name="v2" class=" additional_option_type_8" checked="checked" value="255">
<label class="" for="255">YES</label>
<input type="radio" name="v2" class=" additional_option_type_8" value="256">
<label class="" for="256">NO</label>
Note: Everthing here is made dynamically and i dont have access to change the html so cannot add classes or id to the elements.
Here on change of is_poly_cover if its yes than all radio button goes to yes and if is_poly_cover no than all radio btns goes to No
attempt:
var set_classes = ['additional_option_type_8','additional_option_type_7'];
$('body').delegate('.is_poly_cover', 'change', function(e) {
var is_poly_cover_text = $(".is_poly_cover").find("option:selected").text().toLowerCase();
if(is_poly_cover_text == 'yes'){
var label = '';
var req_elem = '';
for(var i=1;i<set_classes.length;i++) {
req_elem = "."+set_classes[i];
//console.log(req_elem)
label = $(req_elem).next().html().toLowerCase();
console.log(label)
}
}
});
You can use .each loop to iterate through your labels and see if its value match with select if yes add radio checked above it to true.
Demo Code :
$('body').delegate('.is_poly_cover', 'change', function(e) {
var values = $(this).val().toUpperCase();
console.log(values)
//remove checked from radios
$('[class*=additional_option_type_]').prop("checked", false)
//loop through label (give some class to label then change label.thatclass_name)
$("label").each(function() {
//check value is same
if ($(this).text() == values) {
//add checked to radio
$(this).prev().prop("checked", true)
}
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="is_poly_cover">
<option>No</option>
<option>Yes</option>
</select>
<input type="radio" name="v1" class="additional_option_type_7" value="251">
<label class="" for="251">YES</label>
<input type="radio" name="v1" class=" additional_option_type_7" value="254">
<label class="" for="254">NO</label>
<input type="radio" name="v2" class=" additional_option_type_8" value="255">
<label class="" for="255">YES</label>
<input type="radio" name="v2" class=" additional_option_type_8" value="256">
<label class="" for="256">NO</label>
setRadioButton();
$('.is_poly_cover').change(function()
{
setRadioButton();
});
function setRadioButton()
{
if($('.is_poly_cover :selected').text() == "Yes")
{
$('body input[type=radio]').each(function(){
var value = $(this).attr('checkedvalue');
if(value == 1)
{
$(this).prop('checked',true);
}
});
}
else
{
$('body input[type=radio]').each(function(){
var value = $(this).attr('checkedvalue');
if(value == 0)
{
$(this).prop('checked',true);
}
});
}
}
<select class="is_poly_cover">
<option>No</option>
<option>Yes</option>
</select>
<input type="radio" name="v1" class=" additional_option_type_7" checkedvalue="1" checked="checked" value="251">
<label class="" for="251">YES</label>
<input type="radio" name="v1" class=" additional_option_type_7" checkedvalue="0" value="254">
<label class="" for="254">NO</label>
<input type="radio" name="v2" class=" additional_option_type_8" checkedvalue="1" checked="checked" value="255">
<label class="" for="255">YES</label>
<input type="radio" name="v2" class=" additional_option_type_8" checkedvalue="0" value="256">
<label class="" for="256">NO</label>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

jQuery Show/hide inputs based on multiple select options

I have a drop-down which allows multiple product selection and based on the products selected I want to show inputs for products extra and add a required attribute to those inputs.
var products = $('#products').select2({
tags: true
});
products.on('change', function() {
var ids = products.val();
setExtras(ids);
});
function setExtras(ids) {
$.each(ids, function(index, id) {
$('#extras .form-group').each(function() {
if ($(this).hasClass('extra_' + id)) {
$(this).show('fade').find('input').prop('required', true);
} else {
$(this).hide('fade').find('input').prop('required', false);
}
});
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6/js/select2.min.js"></script>
<div class="form-group">
<label for="products">Products</label>
<select multiple="" class="form-control select2" name="products[]" id="products">
<option value="1">Product One</option>
<option value="2">Product Two</option>
</select>
<span class="help-block">Please select your product</span>
</div>
<div id="extras">
<div style="display: none;" class="form-group extra_1">
<label for="1_1">
Product One(Message)
</label>
<input type="text" class="form-control" id="1_1" name="extras[1][1]" placeholder="Your message here">
</div>
<div style="display: none;" class="form-group extra_2">
<label for="2_2">
Product Two(Message)
</label>
<input type="text" class="form-control" id="2_2" name="extras[2][2]" placeholder="Your message here">
</div>
<div style="display: none;" class="form-group extra_2">
<label for="2_3">
Product Two(Tag Line)
</label>
<input type="text" class="form-control" id="2_3" name="extras[2][3]" placeholder="Your tag line here">
</div>
</div>
My current JS code only shows inputs for last selected product, please help me out to fix that.
P.S. The product extras will be variable, some products has one or more extra and some will have none.
You can try change code of function setExtras
function setExtras(ids) {
$('#extras .form-group').each(function () {
$(this).hide('fade').find('input').prop('required', false);
});
$.each(ids, function (index, id) {
$('#extras .form-group').each(function () {
if ($(this).hasClass('extra_' + id)) {
$(this).show('fade').find('input').prop('required', true);
}
});
});
}
This is a demo link: https://codepen.io/phuongnm153/pen/PvwoZg

Usage of radio value in ID selector

Given this html:
<form action="">
<div id="choices">
<input type="radio" name="stype" id="opt1" value="input1_div" checked=""/> Opt1
<input type="radio" name="stype" id="opt2" value="input2_div"/> Opt2
</div>
<div id="stypes">
<div id="input1_div">
<input type="text" id="input1" name="input1" placeholder="input1"/>
</div>
<div id="input2_div" style="display: none;">
<input type="text" id="input2" name="input2" placeholder="input2" disabled=""/>
</div>
</div>
<div id="#sbutton">
<input type="submit" id="input3" value="Submit"/>
</div>
</form>
I use following jQuery to hide/disable input fields based on selected radio buttons:
jQuery('#choices input').each(function() {
var item = this;
$(this).click(function() {
if($('input[type=radio][name=stype]').is(':checked')) {
$('#stypes > div').hide();
$('#stypes input').not("#sbutton").prop('disabled', true);
$('#' + $(item).val()).fadeIn();
$('#' + $(item).val() + ' input').prop('disabled', false);
}
});
});
All-in-One in this jsfiddle.
I'm particularly unsure about my technique to incorporate radio value into the id selector:
$('#' + $(item).val()).fadeIn();
$('#' + $(item).val() + ' input').prop('disabled', false);
What is the correct way to do it? Other tips regarding my jQuery?
First of all, you don't need a sophisticated jQuery.each loop to bind the click and to define this. In each event handler this will be the caller of the function. In your case it is enough to have click function for all of them.
As you said in comments, it's only matter of presentation. I prefer to have one field instead of two fields. Even I prefer to have a fixed name for this text input, though in order to make it very similar to your example I change the name and placeholder accordingly.
$(function(){
$('#choices input').click(function() {
var newName = $(this).val(),
newPlaceholder = $(this).attr("data-placeholder");
$('#interchangable_input[name!='+newName+']').hide()
.attr("name", newName)
.attr("placeholder", newPlaceholder)
.fadeIn();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="">
<div id="choices">
<input type="radio" name="stype" id="opt1" data-placeholder="Input one" value="input1" checked=""/> <label for="opt1">Opt1</label>
<input type="radio" name="stype" id="opt2" data-placeholder="Input two" value="input2"/> <label for="opt2">Opt2</label>
</div>
<div id="stypes">
<input type="text" id="interchangable_input" name="input1" placeholder="Input one"/>
</div>
<div id="#sbutton">
<input type="submit" id="input3" value="Submit"/>
</div>
</form>
Few more suggestions:
You can use <label for="target id"> for each option label in radio buttons or checkboxes. It will work fine with click event handler, even if the user clicks on the label instead of the button itself.
You can hid some information as data-* attribute in html5. You don't need to necessarily use value.
Update for multiple items
In case of group of multiple items in form, I can imagine a form with different sections or pages. The <fieldset> can be use to group these items. In HTML5 you could just disable the fieldset tag by <fieldset disabled> when you change the form page with jquery. (With exception of IE browsers). Because of this exception we need to disable all items in subforms. In order to handle this part, I defined a class .form-element which applies for all form inputs. You can also use <div> instead of <fieldset>, then you will need to track their enable/disable status.
$(function(){
// initialization by disabling form-elements and hiding them
$("#subforms fieldset[disabled]").hide();
$("#subforms fieldset[disabled] .form-element").attr('disabled','disabled');
// choice tracker
$('#choices input').click(function() {
var $target = $($(this).attr("data-subform")),
$oldElement = $("#subforms fieldset:not([disabled])");
$oldElement.attr('disabled','disabled').hide();
$oldElement.find(".form-element").attr('disabled','disabled');
$target.removeAttr("disabled");
$target.find(".form-element").removeAttr("disabled");
$target.fadeIn();
});
});
fieldset {
border: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="">
<div id="choices">
<input type="radio" name="stype" id="opt1" data-subform="#subform1" value="subform1" checked=""/> <label for="opt1">Opt1</label>
<input type="radio" name="stype" id="opt2" data-subform="#subform2" value="subform2"/> <label for="opt2">Opt2</label>
</div>
<div id="subforms">
<fieldset id="subform1" >
<input class="form-element" type="text" name="input1_1" placeholder="Input one"/>
<input class="form-element" type="text" name="input1_2" placeholder="Input two"/>
</fieldset>
<fieldset id="subform2" disabled>
<input class="form-element" type="text" name="input2_1" placeholder="Input one"/><br />
<textarea class="form-element" name="input2_2" placeholder="Input two"></textarea><br />
<input class="form-element" type="checkbox" name="input2_3" id="input2_3" /> <label for="input2_3">check this first</label>
</fieldset>
</div>
<div id="#sbutton">
<input type="submit" id="input3" value="Submit"/>
</div>
</form>

How to display add button at last element after delete last row?

I want to add some more fields with add and remove buttons, when I delete the last record add button must be present at the last element after deleting.
<div id="cont">
<p>
<label>Contact No : </label>
<select>
<option value="Phone">Phone</option>
<option value="Phone">Land Line</option>
<option value="Phone">Fax</option>
</select>
<input type="text" name="website" value="" />
<input type="button" value="+" id="addcontact1" />
</p>
</div>
This is a fiddle link.
http://jsfiddle.net/8dq15j2y/
Add + button after P tag and Replace $('#addcontact1').show(); to $('#addcontact1').hide();
Note: ID of an element must be unique, so use class instead
$(function() {
var scntDiv = $('#cont');
var i = $('#cont p').size() + 1;
$('#cont').on('click', '.addcontact1', function() {
$('<p style="margin-left:150px;"><select><option value="Phone">Phone</option><option value="Land-Line">Land-Line</option><option value="Fax">Fax</option></select><input type="text" id="p_scnt" size="20" name="p_scnt_' + i + '" value="" placeholder="" /> remove <input type="button" value="+" class="addcontact1"></p>').appendTo(scntDiv);
i++;
$(this).hide();
return false;
});
$('#cont').on('click', '.remScnt', function() {
if (i > 2) {
$(this).closest('p').remove();
i--;
}
$('#cont p').last().find('.addcontact1').show();
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div id="cont">
<p>
<label>Contact No :</label>
<select>
<option value="Phone">Phone</option>
<option value="Phone">Land Line</option>
<option value="Phone">Fax</option>
</select>
<input type="text" name="website" value="" />
<input type="button" value="+" class="addcontact1" />
</p>
</div>
Using css: http://jsfiddle.net/arunpjohny/k7t86pkx/3/
you can insert after the line
$(this).parents('p').remove(); with code bellow:
$('#cont p:last').children('#addcontact1').show();

Categories