jQuery does not see the text that was added - javascript

There is a script. It adds text from selects to the tags of the Special Price block. At input of number the new similar block is added. It is necessary to add exactly the same block as the previous one. But the text from the tags <span> (numb, curr) is not added. I understand that this script only parses the original HTML markup?
https://playcode.io/301889?tabs=console&script.js&output
The code:
(function() {
$(document).ready(function() {
$('.field.inline.specially > span.curr').text(
$('#id_lot_currency > option:selected').eq(0).text()
);
$('.field.inline.specially > span.numb').text(
$('#id_lot_type > option:selected').eq(0).text()
);
$(document).on('change','#id_lot_currency',function () {
$('.field.inline.specially span').eq(3).text($('option:selected',this).text())
})
$(document).on('change','#id_lot_type',function () {
$('.field.inline.specially span').eq(1).text($('option:selected',this).text())
});
})
var copy = document.querySelector('.field.inline.specially').cloneNode(true);
document.querySelector('html').addEventListener('input', function(e) {
if (e.target.classList.contains('event') && e.target.tagName == 'INPUT') {
var error = 0;
for (var evt of document.querySelectorAll('.field.inline.specially input.event')) {
evt.value = evt.value.replace(/[^\d]/, '');
if (!evt.value || +evt.value < 1) error++;
}
if (!error) {
var last = document.querySelectorAll('.field.inline.specially');
last[last.length - 1].insertAdjacentHTML('afterEnd', copy.outerHTML);
}
}
});
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="field inline" id="lot_minimum">
<label for="id_lot_minimum" class="subhead">Lot minimum:</label>
<input type="number" name="lot_minimum" required id="id_lot_minimum" />
<select name="lot_type" style="width: 100px" class="select2" id="id_lot_type">
<option value="1">kg</option>
<option value="2">foot</option>
</select>
</div>
<div class="field inline" id='lot'>
<label for="id_lot_cost" class="subhead">Cost:</label>
<input type="number" name="lot_cost" step="0.01" required id="id_lot_cost" />
<select name="lot_currency" style="width: 100px" class="select2" id="id_lot_currency">
<option value="1">usd</option>
<option value="3">blg</option>
<option value="2">uah</option>
</select>
</div>
<div class="field inline specially">
<label for="specially" class="subhead">Special price</label>
<span class="id_specially_price"><input type="text" name="adittional_specially_price" style="width: 165px" class="event" id="" /></span>
<span class='numb'></span>
<span class="id_specially_number"><input type="text" name="adittional_specially_number" style="width: 100px" class="event" id="" /></span>
<span class='curr'></span>
</div>

instead of $('#item').on('change',function) use $(document).on('change','#item',function) which will work on event the injected HTML.

(function() {
$(document).ready(function() {
$('.field.inline.specially > span.curr').text(
$('#id_lot_currency > option:selected').eq(0).text()
);
$('.field.inline.specially > span.numb').text(
$('#id_lot_type > option:selected').eq(0).text()
);
$(document).on('change','#id_lot_currency',function () {
$('.field.inline.specially span.curr').text($('option:selected',this).text())
})
$(document).on('change','#id_lot_type',function () {
$('.field.inline.specially span.numb').text($('option:selected',this).text())
});
})
document.querySelector('html').addEventListener('input', function(e) {
var copy = document.querySelector('.field.inline.specially').cloneNode(true);
if (e.target.classList.contains('event') && e.target.tagName == 'INPUT') {
var error = 0;
for (var evt of document.querySelectorAll('.field.inline.specially input.event')) {
evt.value = evt.value.replace(/[^\d]/, '');
if (!evt.value || +evt.value < 1) error++;
}
if (!error) {
var last = document.querySelectorAll('.field.inline.specially');
last[last.length - 1].insertAdjacentHTML('afterEnd', copy.outerHTML);
}
}
});
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="field inline" id="lot_minimum">
<label for="id_lot_minimum" class="subhead">Lot minimum:</label>
<input type="number" name="lot_minimum" required id="id_lot_minimum" />
<select name="lot_type" style="width: 100px" class="select2" id="id_lot_type">
<option value="1">kg</option>
<option value="2">foot</option>
</select>
</div>
<div class="field inline" id='lot'>
<label for="id_lot_cost" class="subhead">Cost:</label>
<input type="number" name="lot_cost" step="0.01" required id="id_lot_cost" />
<select name="lot_currency" style="width: 100px" class="select2" id="id_lot_currency">
<option value="1">usd</option>
<option value="3">blg</option>
<option value="2">uah</option>
</select>
</div>
<div class="field inline specially">
<label for="specially" class="subhead">Special price</label>
<span class="id_specially_price"><input type="text" name="adittional_specially_price" style="width: 165px" class="event" id="" /></span>
<span class='numb'></span>
<span class="id_specially_number"><input type="text" name="adittional_specially_number" style="width: 100px" class="event" id="" /></span>
<span class='curr'></span>
</div>

Related

Make a multiselect form

I have this select form to add in my database countries.
https://jsfiddle.net/Da4m3/394/
I want to change this form into this:
this is html code:
<label class="margin-right10"><input type="radio" id="members_create_campaign_form_countrySelectionType_0" name="members_create_campaign_form[countrySelectionType]" required="required" value="0" checked="checked" /> All</label>
<label class="margin-right10"><input type="radio" id="members_create_campaign_form_countrySelectionType_1" name="members_create_campaign_form[countrySelectionType]" required="required" value="1" /> Selected</label>
<div id="clist_div" class="simplebox cgrid540-right" style="display:none;">
<div style="padding:5px"></div>
<div class="simplebox cgrid200-left">
<p style="text-align:center;"><b>Excluded Countries</b></p>
<select size="10" name="excludedcountries" style="width:200px; height:160px;" onDblClick="moveSelectedOptions(this.form['excludedcountries'],this.form['members_create_campaign_form[countries][]'])" multiple >
<option value='97'>Afghanistan</option>
<option value='191'>Aland Islands</option>
<option value='105'>Albania</option>
<option value='114'>Algeria</option>
</select>
</div>
<div class="simplebox cgrid40-left">
<input class="button-blue" type="button" name="right" value=">>" onclick="moveSelectedOptions(this.form['excludedcountries'],this.form['members_create_campaign_form[countries][]'])"><br/><br/>
<input class="button-blue" type="button" name="left" value="<<" onclick="moveSelectedOptions(this.form['members_create_campaign_form[countries][]'],this.form['excludedcountries'])">
</div>
<div class="simplebox cgrid200-left">
<p style="text-align:center;"><b>Selected Countries</b></p>
<select size="10" id="members_create_campaign_form_countries" name="members_create_campaign_form[countries][]" style="width:200px; height:160px;" onDblClick="moveSelectedOptions(this.form['members_create_campaign_form[countries][]'],this.form['excludedcountries'])" multiple >
</select>
and with this js:
$(document).ready(function () {
if ($('#members_create_campaign_form_countrySelectionType_1').is(':checked')) {
$('#clist_div').show('slow');
}
$('#members_create_campaign_form_countrySelectionType_0').click(function () {
$('#clist_div').hide('slow');
});
$('#members_create_campaign_form_countrySelectionType_1').click(function () {
$('#clist_div').show('slow');
});
selectDiff('clist_div', 'members_create_campaign_form_countries');
});
function sortSelect(selElem) {
var tmpAry = new Array();
for (var i=0;i<selElem.options.length;i++) {
tmpAry[i] = new Array();
tmpAry[i][0] = selElem.options[i].text;
tmpAry[i][1] = selElem.options[i].value;
}
tmpAry.sort();
while (selElem.options.length > 0) {
selElem.options[0] = null;
}
for (var i=0;i<tmpAry.length;i++) {
var op = new Option(tmpAry[i][0], tmpAry[i][1]);
selElem.options[i] = op;
}
return;
}
function SelectAllList(CONTROL){
for(var i = 0;i < CONTROL.length;i++){
CONTROL.options[i].selected = true;
}
}
function hasOptions(obj) {
if (obj!=null && obj.options!=null) {
return true;
}
return false;
}
function moveSelectedOptions(from,to) {
if (!hasOptions(from)) { return; }
for (var i=0; i<from.options.length; i++) {
var o = from.options[i];
if (o.selected) {
if (!hasOptions(to)) { var index = 0; } else { var index=to.options.length; }
to.options[index] = new Option( o.text, o.value, false, false);
}
}
// Delete them from original
for (var i=(from.options.length-1); i>=0; i--) {
var o = from.options[i];
if (o.selected) {
from.options[i] = null;
}
}
if ((arguments.length<3) || (arguments[2]==true)) {
sortSelect(from);
sortSelect(to);
}
from.selectedIndex = -1;
to.selectedIndex = -1;
}
how i can do that? i have tried but all time don't insert in to my database!
Is from this value allTarget that put me all, and this value countries[] for multiselect, i don't know where and how i can put this values.
I have do some modifications and i have this code that when i select from left side is working, is adding to my database but when i push options to right side is not adding in database.
<div class="st-form-line">
<span class="st-labeltext">Countries</span>
<label class="margin-right10"><input type="radio" id="members_create_campaign_form_countrySelectionType_0" name="www" required="required" value="0" checked="checked" /> All</label>
<label class="margin-right10"><input type="radio" id="members_create_campaign_form_countrySelectionType_1" name="www" required="required" value="1"/> Selected</label>
<div id="clist_div" class="simplebox cgrid540-right" style="display:none;">
<div style="padding:5px"></div>
<div class="simplebox cgrid200-left">
<p style="text-align:center;"><b>Excluded Countries</b></p>
<select size="10" name="countries[]" style="width:200px; height:160px;" onDblClick="moveSelectedOptions(this.form['countries[]'],this.form['countries[]'])" multiple >
<?php foreach($arrayCountries as $country) {?>
<option value="<?= $country ?>" ><?= $country ?></option>
<?php } ?>
</select>
</div>
<div class="simplebox cgrid40-left">
<input class="button-blue" type="button" name="right" value=">>" onclick="moveSelectedOptions(this.form['countries[]'],this.form['countries[]'])"><br/><br/>
<input class="button-blue" type="button" name="left" value="<<" onclick="moveSelectedOptions(this.form['[countries[]'],this.form['countries[]'])">
</div>
<div class="simplebox cgrid200-left">
<p style="text-align:center;"><b>Selected Countries</b></p>
<select size="10" id="members_create_campaign_form_countries" name="countries[]" style="width:200px; height:160px;" onDblClick="moveSelectedOptions(this.form ['countries[]'],this.form['countries[]'])" multiple >
</select>
</div>
</div>
<div class="clear"></div>
</div>
Quickly coded, but is this what you're looking for?
https://jsfiddle.net/Da4m3/398/
(didn't bother to write the css)
The magic happens in the js code
s = $('#selected');
n = $('#not-selected');
l = $('#left');
r = $('#right');
l.on('click', function() {
move = s.find('option:checked');
move.attr('selected', false);
n.append(move);
});
r.on('click', function() {
move = n.find('option:checked');
move.attr('selected', false);
s.append(move);
});

Do not repeat yourself best practices showing and hiding fields

I am trying to figure out the best way to show and hide fields that are being reused. Cleaning up the code so that I do not repeat myself "DRY". Will someone please assist me in the best practices of doing so?
What I have is a select that allows the user to choose from two different reports.
<select class="form-control" id="reporttype" name="reporttype">
<option value="" selected="selected">Select Report</option>
<option id ="checklistreport" value="checklistreport" >Checklist Stats</option>
<option id ="locationreport" value="locationreport" >Location Stats</option>
</select>
Then each report have a lot of similar fields. How can I have them use the same fields but hide/show the differences and go to the correct form "action" based which report is chosen.
Location Report
<form name="generatereport" method="post" action="_location_queries.cfm">
<select name="Location" id="loc" multiple="multiple" required size="9">
<option value="OPERATIONS">Operations</option>
<option value="CCC">Contact Center</option>
<option value="QA">QA Department</option>
<option value="DS">DeSoto</option>
<option value="PS">Palma Sola</option>
<option value="LWR">Lakewood Ranch</option>
<option value="NR">North River</option>
<option value="SDL">SDL</option>
<option value="FSC">FSC</option>
</select>
<button id="add" type="button">ADD ALL</button>
<button id="rem" type="button">REMOVE ALL</button>
<textarea id="selected" rows="10" readonly></textarea>
<br /><br />
<label for="StartDate">From</label>
<input type='text' name="StartDate" id="StartDate" value="" required/>
<br /><br />
<label for="EndDate">To</label>
<input type='text' name="EndDate" id="EndDate" value="" required/>
<br /><br />
<label for="Format">Format</label>
<select name="Format" required>
<option selected value="">Select Format</option>
<option value="print">Print</option>
<option value="pdf">Preview</option>
<option value="xls">Excel</option>
</select>
<br /><br />
<input type="submit" name="submit" value="Continue" />
</form>
<script type="text/javascript">
var opts = document.querySelectorAll('#loc option');
document.getElementById('add').addEventListener('click', function() {
for ( var i=0; i<opts.length; i++ ) {
opts[i].selected = true;
}
reflectChange();
});
document.getElementById('rem').addEventListener('click', function() {
for ( var i=0; i<opts.length; i++ ) {
opts[i].selected = false;
}
reflectChange();
});
document.getElementById('loc').addEventListener('change', reflectChange);
function reflectChange() {
document.getElementById('selected').value = '';
for ( var i=0; i<opts.length; i++ ) {
if(opts[i].selected)
document.getElementById('selected').value += opts[i].text+'\n';
}
}
</script>
Checklist Report
<form name="generatereport" method="post" action="_checklists_queries.cfm">
<select name="Location" id="loc" multiple="multiple" required size="8">
<option value="OPERATIONS">Operations</option>
<option value="CCC">Contact Center</option>
<option value="QA">QA Department</option>
<option value="DS">DeSoto</option>
<option value="PS">Palma Sola</option>
<option value="LWR">Lakewood Ranch</option>
<option value="NR">North River</option>
<option value="SDL">SDL</option>
<option value="FSC">FSC</option>
</select>
<button id="add" type="button">ADD ALL</button>
<button id="rem" type="button">REMOVE ALL</button>
<textarea id="selected" rows="7" readonly></textarea>
<br /><br />
<cfquery name="GetActiveEmps" datasource="tco_associates">
SELECT assoc_userid, assoc_last, assoc_first FROM tco_associates
WHERE assoc_status = 'ACTIVE'
and assoc_last NOT LIKE 'Test%'
and len(assoc_last) > 0
ORDER BY assoc_last
</cfquery>
<select name="EmployeeName" id="EmployeeName" multiple="multiple" required size="8">
<cfoutput query="GetActiveEmps">
<option value="#assoc_userid#">#Trim(assoc_last)#, #Trim(assoc_first)#</option>
</cfoutput>
</select>
<button id="add1" type="button">ADD ALL</button>
<button id="rem1" type="button">REMOVE ALL</button>
<textarea id="selected1" rows="7" readonly></textarea>
<br /><br />
<label for="StartDate">From</label>
<input type='text' name="StartDate" id="StartDate" value="" required/>
<br /><br />
<label for="EndDate">To</label>
<input type='text' name="EndDate" id="EndDate" value="" required/>
<br /><br />
<label for="Format">Format</label>
<select name="Format" required>
<option selected value="">Select Format</option>
<option value="print">Print</option>
<option value="pdf">Preview</option>
<option value="xls">Excel</option>
</select>
<br /><br />
<input type="submit" name="submit" value="Continue" />
</form>
<script type="text/javascript">
// JS for Showing Chosen Locations in textarea
var opts = document.querySelectorAll('#loc option');
document.getElementById('add').addEventListener('click', function() {
for ( var i=0; i<opts.length; i++ ) {
opts[i].selected = true;
}
reflectChange();
});
document.getElementById('rem').addEventListener('click', function() {
for ( var i=0; i<opts.length; i++ ) {
opts[i].selected = false;
}
reflectChange();
});
document.getElementById('loc').addEventListener('change', reflectChange);
function reflectChange() {
document.getElementById('selected').value = '';
for ( var i=0; i<opts.length; i++ ) {
if(opts[i].selected)
document.getElementById('selected').value += opts[i].text+'\n';
}
}
// End JS for Showing Chosen Locations in textarea
// JS for Showing Chosen Associates in textarea
var opts1 = document.querySelectorAll('#EmployeeName option');
document.getElementById('add1').addEventListener('click', function() {
for ( var i=0; i<opts1.length; i++ ) {
opts1[i].selected = true;
}
reflectChange1();
});
document.getElementById('rem1').addEventListener('click', function() {
for ( var i=0; i<opts1.length; i++ ) {
opts1[i].selected = false;
}
reflectChange1();
});
document.getElementById('EmployeeName').addEventListener('change', reflectChange1);
function reflectChange1() {
document.getElementById('selected1').value = '';
for ( var i=0; i<opts1.length; i++ ) {
if(opts1[i].selected)
document.getElementById('selected1').value += opts1[i].text+'\n';
}
}
// End JS for Showing Chosen Associates in textarea
</script>
Many of these fields are the same is there a way i can just have one set and show them if either option is chosen and not have two different sets?
This is what I have tried:
<select class="form-control" id="reporttype" name="reporttype">
<option value="" selected="selected">Select Report</option>
<option id ="checklistreports" value="checklistreports" >Checklist Stats</option>
<option id ="locationreports" value="locationreports" >Location Stats</option>
</select>
<script>
$(document).on('change', '#reporttype', function() {
var value = $(this).val();
//var checklistreport = $("#checklistreport");
//var locationreport = $("#locationreport");
var location = $("#location");
var employeelist = $("#employeelist");
var chosendates = $("#chosendates");
var formattype = $("#formattype");
var submitbtn = $("#submitbtn");
if (value == "checklistreports") {
//checklistreport.show();
//locationreport.hide();
location.show();
employeelist.show();
chosendates.show();
formattype.show();
submitbtn.show();
} else if (value == "locationreports") {
//checklistreport.hide();
//locationreport.show();
location.show();
employeelist.hide();
chosendates.show();
formattype.show();
submitbtn.show();
} else {
//checklistreport.hide();
//locationreport.hide();
location.hide();
employeelist.hide();
chosendates.hide();
formattype.hide();
submitbtn.hide();
}
});
</script>
<br /><br />
<!--<div id="locationreport" style="display: none;">-->
<form name="generatereport" method="post" action="_location_queries.cfm">
<!--<div id="checklistreport" style="display: none;">-->
<form name="generatereport" method="post" action="_checklists_queries.cfm">
</form>
<div id="location" style="display: none;">
<select name="Location" id="loc" multiple="multiple" required size="9">
<option value="OPERATIONS">Operations</option>
<option value="CCC">Contact Center</option>
<option value="QA">QA Department</option>
<option value="DS">DeSoto</option>
<option value="PS">Palma Sola</option>
<option value="LWR">Lakewood Ranch</option>
<option value="NR">North River</option>
<option value="SDL">SDL</option>
<option value="FSC">FSC</option>
</select>
<button id="add" type="button">ADD ALL</button>
<button id="rem" type="button">REMOVE ALL</button>
<textarea id="selected" rows="10" readonly></textarea>
</div>
<br /><br />
<div id="employeelist" style="display: none;">
<cfquery name="GetActiveEmps" datasource="tco_associates">
SELECT assoc_userid, assoc_last, assoc_first FROM tco_associates
WHERE assoc_status = 'ACTIVE'
and assoc_last NOT LIKE 'Test%'
and len(assoc_last) > 0
ORDER BY assoc_last
</cfquery>
<select name="EmployeeName" id="EmployeeName" multiple="multiple" required size="9">
<cfoutput query="GetActiveEmps">
<option value="#assoc_userid#">#Trim(assoc_last)#, #Trim(assoc_first)#</option>
</cfoutput>
</select>
<button id="add1" type="button">ADD ALL</button>
<button id="rem1" type="button">REMOVE ALL</button>
<textarea id="selected1" rows="10" readonly></textarea>
</div>
<br /><br />
<div id="chosendates" style="display: none;">
<label for="StartDate">From</label>
<input type='text' name="StartDate" id="StartDate" value="" required/>
<br /><br />
<label for="EndDate">To</label>
<input type='text' name="EndDate" id="EndDate" value="" required/>
</div>
<br /><br />
<div id="formattype" style="display: none;">
<label for="Format">Format</label>
<select name="Format" required>
<option selected value="">Select Format</option>
<option value="print">Print</option>
<option value="pdf">Preview</option>
<option value="xls">Excel</option>
</select>
</div>
<br /><br />
<div id="submitbtn" style="display: none;">
<input type="submit" name="submit" value="Continue" />
</div>
</form>
<script type="text/javascript">
// JS for Showing Chosen Locations in textarea
var opts = document.querySelectorAll('#loc option');
document.getElementById('add').addEventListener('click', function() {
for ( var i=0; i<opts.length; i++ ) {
opts[i].selected = true;
}
reflectChange();
});
document.getElementById('rem').addEventListener('click', function() {
for ( var i=0; i<opts.length; i++ ) {
opts[i].selected = false;
}
reflectChange();
});
document.getElementById('loc').addEventListener('change', reflectChange);
function reflectChange() {
document.getElementById('selected').value = '';
for ( var i=0; i<opts.length; i++ ) {
if(opts[i].selected)
document.getElementById('selected').value += opts[i].text+'\n';
}
}
// End JS for Showing Chosen Locations in textarea
// JS for Showing Chosen Associates in textarea
var opts1 = document.querySelectorAll('#EmployeeName option');
document.getElementById('add1').addEventListener('click', function() {
for ( var i=0; i<opts1.length; i++ ) {
opts1[i].selected = true;
}
reflectChange1();
});
document.getElementById('rem1').addEventListener('click', function() {
for ( var i=0; i<opts1.length; i++ ) {
opts1[i].selected = false;
}
reflectChange1();
});
document.getElementById('EmployeeName').addEventListener('change', reflectChange1);
function reflectChange1() {
document.getElementById('selected1').value = '';
for ( var i=0; i<opts1.length; i++ ) {
if(opts1[i].selected)
document.getElementById('selected1').value += opts1[i].text+'\n';
}
}
// End JS for Showing Chosen Associates in textarea
</script>
Not sure how I choose which action for the form. Depending on which report is chosen.
https://jsfiddle.net/bobrierton/o2gxgz9r/10018/
You have a few options here:
Option #1:
Always show the "common" inputs, and only hide the inputs that are conditional upon selection, that way your code is cleaner because you only have to manage the conditional elements (not all of them as you are doing now)
Option #2:
Use CF includes to hold your "common" elements, and "conditional" elements, combining them where necessary to build the correct list.
Option #3:
Use JavaScript to hold your "common" elements, and "conditional" elements, and render the composed list based on your conditions.
var location = $('select[name=Location]');
// This lists could hold anything you want, jQuery elements
// references, strings, etc.
var lists = {
common: ['a', 'b', 'c'],
locationreports: ['location #1', 'location #2'],
checklistreports: ['checklist #1', 'checklist #2']
};
$('#reporttype').on('change', function() {
var value = $(this).val();
// Grab a copy of the common list to begin with
var options = [].concat(lists.common);
// Now combine the conditional options
if (value === "checklistreports" || value === "locationreports") {
options = options.concat(lists[value]);
}
// Now you have a complete list of options to show based
// your conditions, so now you can just show them all, or
// do whatever you want with this new list.
location.empty();
options.forEach(function($element) {
// Do something with the list
location.append('<option value="' + $element + '">' + $element + '</option>');
})
There are lots of other options, but between using and combining includes, or composing objects together you should be able to customize a nice DRY workflow.

dynamically add and removing div with javascript

presently stuck in situation. trying to create a form where one can dynamically add and remove div elements where necessary,so far have been a to DYNAMICALLY ADD, problem is if i try to REMOVE div,only the last created gets to delete whilst others remain(excluding the parent div)KINDLY ASSIST.
<!doctype html>
<html lang="en">
<head>
</head>
<body>
<div id="box">
<div id='div' style="background: #99CCFF; height: 100px; width:300px" >
<p>Degree Level: <select id="dropdown">
<option value="Doctorate Degree">Doctorate Degree</option>
<option value="Masters">Masters</option>
<option value="Bachelors Degree">Bachelors Degree</option>
<option value="SSCE">SSCE</option>
</select></p>
<label for="firstname">School Name</label>
<input type="text" placeholder="Your Role"">
<label for="from">From</label>
<input type="text" id="from" name="from">
<br>
<label for="to">to</label>
<input type="text" id="to" name="to">
</div>
</div>
<div>
<button id="submit1">Add new div</button>
<input type="button" value="Remove Element"
onClick="removeElement('box','div');">
</div>
</body>
<script>
var box = document.getElementById('box'),
template = box.getElementsByTagName('div'),
template = template[0];
var counter = 1;
submit1.onclick = function () {
var new_field = template.cloneNode(true);
new_field.id = new_field.id + counter++
console.log(new_field.id)
box.appendChild(new_field);
return false;
};
</script>
<script>
function removeElement(boxDiv, divDiv){
if (divDiv == boxDiv) {
alert("The parent div cannot be removed.");
}
else if (document.getElementById(divDiv)) {
var div = document.getElementById(divDiv);
var box = document.getElementById(boxDiv);
box.removeChild(div);
}
else {
alert("Child div has already been removed or does not exist.");
return false;
}
}
You are passing the string div to your remove element function which will only remove the first div.
You can find all the children elements and then remove the last child
Building on your previous code, see the snippet below
var box = document.getElementById('box'),
template = box.getElementsByTagName('div'),
template = template[0];
console.log(template);
var counter = 1;
submit1=document.getElementById("submit1");
submit1.onclick = function () {
var new_field = template.cloneNode(true);
new_field.id = new_field.id + counter++
console.log(new_field.id)
box.appendChild(new_field);
return false;
};
function removeElement(boxDiv){
var box = document.getElementById(boxDiv);
if(box.children){
console.log(box.children);
box.children[box.children.length-1].outerHTML="";
}
}
<div id="box">
<div id='div' style="background: #99CCFF; height: 100px; width:300px" >
<p>Degree Level: <select id="dropdown">
<option value="Doctorate Degree">Doctorate Degree</option>
<option value="Masters">Masters</option>
<option value="Bachelors Degree">Bachelors Degree</option>
<option value="SSCE">SSCE</option>
</select></p>
<label for="firstname">School Name</label>
<input type="text" placeholder="Your Role"">
<label for="from">From</label>
<input type="text" id="from" name="from">
<br>
<label for="to">to</label>
<input type="text" id="to" name="to">
</div>
</div>
<div>
<button id="submit1">Add new div</button>
<input type="button" value="Remove Element"
onClick="removeElement('box');">
</div>
It might be because js thinks you're only selecting the last one when doing
var div = document.getElementById(divDiv);
Try doing a loop until document.getElementById(divDiv) is undefined

How do I enable my form's submit button using jquery?

I have a basic form with some input fields and a dropdown(select field).
Almost all fields have a form of validation. When a field has an error, an error message with the CSS class 'errorText' is displayed next to the field.
By default, my submit button is 'disabled'. I want to remove the 'disabled' attribute from my submit button once all tags with 'errorText' CSS classes are hidden/removed.
my current script just hides all tags with 'errorText' when an error occurs. how do I stop it from doing that and how can I enable my submit button once all fields have been properly enter/validated? Thanks.
EDIT: SOLVED. CODE UPDATED.
// Field Validations
$('#firstName')
.on('blur', function() {
var $this = $(this);
if ($this.val() == '') {
$('label[for="firstName"]').addClass('errorText');
$('#errorFName').show();
} else {
$('label[for="firstName"]').removeClass('errorText');
$('#errorFName').hide();
}
});
$('#lastName')
.on('blur', function() {
var $this = $(this);
if ($this.val() == '') {
$('label[for="lastName"]').addClass('errorText');
$('#errorLName').show();
} else {
$('label[for="lastName"]').removeClass('errorText');
$('#errorLName').hide();
}
});
$('#state')
.on('blur', function() {
var $this = $(this);
if ($('#state').val() == "") {
$('label[for="state"]').addClass('errorText');
$('#errorState').show();
} else {
$('label[for="state"]').removeClass('errorText');
$('#errorState').hide();
}
});
// Submit Button validation
$('input, select').on('keyup, blur', function() {
if ($('.errorText:visible').length ||
$('#firstName' || '#lastName' || '#state').val() == '' ) {
$('input[type="submit"]').prop('disabled', true);
} else if ($('#firstName').val() != '' &&
$('#lastName').val() != '' &&
$('#state').val() != '' ) {
$('input[type="submit"]').prop('disabled', false);
}
});
.errorText {
color: #c4161c;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<div>
<label for="firstName" class="required">First Name</label>
</div>
<div>
<input type="text" name="firstName" id="firstName" />
</div>
<div class="errorText" id="errorFName" style="display:none;">Please enter a First Name</div>
<br />
<div>
<label for="lastName" class="required">Last Name</label>
</div>
<div>
<input type="text" name="lastName" id="lastName" />
</div>
<div class="errorText" id="errorLName" style="display:none;">Please enter a Last Name</div>
<br />
<div>
<label for="state" class="required">State</label>
</div>
<div>
<select name="state" id="state">
<option value="">Select State</option>
<option value="alabama">Alabama</option>
<option value="alaska">Alaska</option>
<option value="arizona">Arizona</option>
<option value="arkansas">Arkansas</option>
<option value="california">California</option>
<option value="etc">etc..</option>
</select>
</div>
<div class="errorText" id="errorState" style="display:none;">Please select a State</div>
<br />
<input type="submit" class="LargeButton" value="Submit Referral" disabled />
If it helps, check this update using data-attribute. We group the label,input,error in a div and handle error message. Also simplified the check valid on input and select element but can be modified.
html
<div>
<label for="firstName" class="required">First Name</label>
<input type="text" name="firstName" id="firstName" />
<span class="errorText" style="display:none;">Please enter a First Name</span>
</div>
<br />
<div>
<label for="lastName" class="required">Last Name</label>
<input type="text" name="lastName" id="lastName" />
<span class="errorText" style="display:none;">Please enter a Last Name</span>
</div>
<br />
<div>
<label for="state" class="required">State</label>
<select name="state" id="state" data-valid="">
<option value="">Select State</option>
<option value="alabama">Alabama</option>
<option value="alaska">Alaska</option>
<option value="arizona">Arizona</option>
<option value="arkansas">Arkansas</option>
<option value="california">California</option>
<option value="etc">etc..</option>
</select>
<span class="errorText" style="display:none;">Please select a State</span>
</div>
<br />
<input type="submit" id="submit" class="LargeButton" value="Submit Referral" disabled />
script
$(function() {
$('input,select')
.on('blur', function() {
var $this = $(this);
if ($this.val() == '') {
$this.data("valid", 'false');
//find the immediate span with errorText and show it
$this.next("span.errorText").show();
} else {
$this.data("valid", 'true');
$this.next("span.errorText").hide();
}
checkInputs();
});
});
function checkInputs() {
//find all the input and select items where the data attribute valid is present and make an array
var array = $('input,select').map(function() {
return $(this).data("valid");
}).get();
//if there are not empty or false indicating invalid value set submit property to true
if (array.indexOf("") == -1 && array.indexOf("false") == -1) {
$("#submit").prop("disabled", false);
} else {
$("#submit").prop("disabled", true);
}
}
css
.errorText {
color: #c4161c;
display: block;
}

Dropdown Menu That Creates An Input Field

What I would like to happen is when somebody selects the commercial option the email-signup1 pops up below it. This is the code I have:
<div class="field-widget">
<select id="field7" name="field227" class="validate-selection"
title="What Type Of Vehicle Is This">
<option >Select one...</option>
<option value="Commercial">Commercial</option>
<option value="Passenger">Passenger</option>
</select>
<div id="email-signup1" class="form-row" style="display:none;">
<div class="field-label"><label for="field22">Email</label>:</div>
<div class="field-widget"><input name="field22" id="field22"
class="required validate-email" title="Optional: Enter your email address" /></div>
</div>
Here is how you can do this with pure JavaScript: http://jsfiddle.net/dfj8u/3/
HTML
<div class="field-widget">
<select id="field7" name="field227" class="validate-selection"
title="What Type Of Vehicle Is This">
<option >Select one...</option>
<option value="Commercial">Commercial</option>
<option value="Passenger">Passenger</option>
</select>
<div id="email-signup1" class="form-row" style="display:none;">
<div class="field-label"><label for="field22">Email</label>:</div>
<div class="field-widget"><input name="field22" id="field22" class="required validate-email" title="Optional: Enter your email address" />
<br /><input type="button" id="closeButton" value="Close" />
</div>
</div>
CSS
.form-row {
width: 200px;
background: gray;
border: 1px solid black;
}
JS
(function () {
var select = document.getElementById('field7'),
closeButton = document.getElementById('closeButton');
function addHandler(el, event, handler) {
if (el.addEventListener) {
el.addEventListener (event, handler, false);
} else if (el.attachEvent) {
el.attachEvent (event, handler);
}
}
addHandler(select, 'change', inputChanged);
addHandler(closeButton, 'click', hideForm);
function inputChanged(event) {
if (this.value === 'Commercial') {
showForm();
}
}
function showForm() {
var form = document.getElementById('email-signup1');
form.style.display = 'block';
}
function hideForm() {
var form = document.getElementById('email-signup1');
form.style.display = 'none';
}
}());
Best regards.

Categories

Resources