Problem with a days select in javascript - javascript

I've a problem with three selects for birth of date (Day,Month,Year) in IE. This is the HTML.
<li><label for="dobYear">Date of birth*:</label>
<select name="dobDay" id="dobDay">
<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>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
<option value="31">31</option>
</select>
<select name="dobMonth" id="dobMonth" onchange="getDays();">
<option value="01">Jan</option>
<option value="02">Fev</option>
<option value="03">Mar</option>
<option value="04">Apr</option>
<option value="05">May</option>
<option value="06">Jun</option>
<option value="07">Jul</option>
<option value="08">Aug</option>
<option value="09">Sep</option>
<option value="10">Oct</option>
<option value="11">Nov</option>
<option value="12">Dec</option>
</select>
<select name="dobYear" id="dobYear" onchange="getDays();">
<option value="2010">2010</option>
<option value="2009">2009</option>
<option value="2008">2008</option>
<option value="2007">2007</option>
<option value="2006">2006</option>
<option value="2005">2005</option>
</select>
</li>
and I have a javascript code to count number of days in every month/year
function getDays()
{
var month = document.getElementById("dobMonth").options[document.getElementById("dobMonth").selectedIndex].value;
var year=document.getElementById("dobYear").options[document.getElementById("dobYear").selectedIndex].value;
var daysoutput;
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12){
var j = 31;
}
else if (month == 4 || month == 6 || month == 9 || month == 11){
var j = 30;
}
else{
if (year%4==0){
j=29;
}
else{
j=28;
}
}
for (var i=1;i<=j;i++){
daysoutput+='<option value="'+i+'">'+i+'</option>';
}
document.getElementById('dobDay').innerHTML=daysoutput;
}
with FF, this is okay, but in IE instead after selecting a month/year , the days select becomes empty!
and I don't know why? ,but I doubt the problem is with innerHTML.
thank you

The proper way to add options is using the .add() method of the options collection of the drop down element.
Working example:
window.onload = function WindowLoad() {
var dtNow = new Date();
var year = dtNow.getFullYear();
FillDropDownRange("ddlMonth", 1, 12, dtNow.getMonth() + 1);
FillDropDownRange("ddlYear", year - 5, year, year);
FillDays();
};
function FillDropDownRange(oDDL, rangeStart, rangeEnd, nSelectedValue) {
if (typeof oDDL == "string")
oDDL = document.getElementById(oDDL);
while (oDDL.options.length > 0)
oDDL.removeChild(oDDL.options[0]);
for (var i = rangeStart; i <= rangeEnd; i++) {
var option = new Option();
option.text = i + "";
option.value = i + "";
if (typeof nSelectedValue != "undefined" && i == nSelectedValue)
option.selected = "selected";
oDDL.options.add(option);
}
}
function FillDays() {
var month = parseInt(document.getElementById("ddlMonth").value);
var year = parseInt(document.getElementById("ddlYear").value);
var date = new Date();
date.setDate(1);
date.setMonth(month - 1);
date.setFullYear(year);
var daysCount = 0;
while (date.getMonth() == (month - 1)) {
date.setDate(date.getDate() + 1);
daysCount++;
}
FillDropDownRange("ddlDay", 1, daysCount);
}
<select id="ddlDay"></select> /
<select id="ddlMonth" onchange="FillDays();"></select> /
<select id="ddlYear" onchange="FillDays();"></select>
I also gave "safe" way to get the number of days given specific month and year.

Thank you friends , I've solved the problem and it's now okey with IE:
this is the solution:
I changed this line :
<label for="dobYear">Date of birth*:</label><select name="dobDay" id="dobDay"> in the html code to this
to this ;
<span id="days"><label for="dobYear">Date of birth*:</label>
<select name="dobDay" id="dobDay">
as you can see , I've added a container (parent) span to select
then I changed the js code as follows:
for (var i=1;i<=j;i++){
daysoutput+='<option value="'+i+'">'+i+'</option>';
}
document.getElementById('dobDay').innerHTML=daysoutput;
becomes :
for (var i=1;i<=j;i++){
daysoutput+='<option value="'+i+'">'+i+'</option>';
}
document.getElementById("days").innerHTML='<label for="dobYear">Date of birth*:</label><select name="dobDay" id="dobDay">'+daysoutput+'</select></label>';
it may appear that IE doesn't apply the innerHTML to a select tag, then I've added a span tag that contains this select , and changed its innerHTML with javascript
thank you

You can not set the innerHTML of a select element with Internet Explorer.
You should be using new Option().
var sel = document.getElementById("mySelect");
sel.options.length = 0; //removes all options
for(var i=0;i<3;i++){
var newOpt = new Option("text" + i, "value" + i);
sel.options[i] = newOpt;
}
You could also use createElement instead of new Option.

I think you should try to case your option value to string or parseInt to compare. It might fixed your problem. For instance:
if(month == 3)
to
if(month == "3")
or
if(parseInt(month) == 3)

Related

Run a function onblur when only when none of 3 inputs have focus [duplicate]

This question already has answers here:
How to validate a date?
(11 answers)
Closed 3 years ago.
I need to accept the start date of an event in an HTML form
Created 3 Separate select boxes for date, month, and time as follows
I want to run an onblur function on any of the boxes and should return false
if any other 2 boxes have focus
<script type="text/javascript">
function chkStartDate(str) {
var dd = document.getElementById("startDD");
var mm = document.getElementById("startMM");
var yy = document.getElementById("startYY");
var err = document.getElementById("dateerr");
var focus = document.activeElement;
if (focus == dd || focus == mm || focus == yy) {
err.style.display = "block";
err.innerHTML = "Still in Focus";
return true;
} else {
if (dd.value == "" || mm.value == "" || yy.value == "") {
err.style.display = "block";
err.innerHTML = "Invalid Start Date";
} else {
var d = new date();
d.setDate(dd.value);
d.setMonth(mm.value);
d.setFullYear(yy.value);
err.style.display = "block";
err.innerHTML = !isNaN(d.valueOf());
return true;
}
}
}
</script>
<html>
<body>
<form name=event method=post action=xxx.asp>
<font face=Verdana Style="FONT-SIZE: 12px"><b><i>Start Date</i></b></font>
<Select id=startDD name=startDD style="border:blue 1px solid;font-size:12px;font-family:verdana;color:black;" onblur=chkStartDate( "dddd")>
<Option value="">DD</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>
<Option value="10">10</option>
<Option value="11">11</option>
<Option value="12">12</option>
<Option value="13">13</option>
<Option value="14">14</option>
<Option value="15">15</option>
<Option value="16">16</option>
<Option value="17">17</option>
<Option value="18">18</option>
<Option value="19">19</option>
<Option value="20">20</option>
<Option value="21">21</option>
<Option value="22">22</option>
<Option value="23">23</option>
<Option value="24">23</option>
<Option value="25">25</option>
<Option value="26">26</option>
<Option value="27">27</option>
<Option value="28">28</option>
<Option value="29">29</option>
<Option value="30">30</option>
<Option value="31">31</option>
</Select>
<Select id=startMM name=startMM style="border:blue 1px solid;font-size:12px;font-family:verdana;color:black;" onblur=chkStartDate( "mmmm")>
<Option value="">MM</option>
<Option value="0">Jan</option>
<Option value="1">Feb</option>
<Option value="2">Mar</option>
<Option value="3">Apr</option>
<Option value="4">May</option>
<Option value="5">June</option>
<Option value="6">Jul</option>
<Option value="7">Aug</option>
<Option value="8">Sep</option>
<Option value="9">Oct</option>
<Option value="10">Nov</option>
<Option value="11">Dec</option>
</Select>
<Select id=startYY name=startYY style="border:blue 1px solid;font-size:12px;font-family:verdana;color:black;" onblur=chkStartDate( "yyyy")>
<Option value="">YYYY</option>
<Option value="2019">2019</option>
<Option value="2020">2020</option>
<Option value="2021">2021</option>
<Option value="2022">2022</option>
<Option value="2023">2023</option>
<Option value="2024">2024</option>
<Option value="2025">2025</option>
</Select>
<font face=verdana style="font-size:10px"><i>(Start Date in DD/MM/YYYY Format)</i></font>
<font style="font-size:4px"><br><br></font>
<font face=Verdana Style="FONT-SIZE: 11px" color=red><b>
<span id="dateerr" style="display:none"></span></b></font>
</form>
</body>
</html>
I want the onblur event to validate the date only if focus is not on any of the 3 select boxes (not happening)
For your second point to validate the date :
Create a date object by passing the iso string representation of your date
Create an iso string representation of your date
Ensure this two string are identical
new Date("2019-04-31T00:00:00.000Z").toJSON() // "2019-05-01T00:00:00.000Z"
function validateDate(dd, mm, yyyy)
{
dd = (dd < 10) ? "0"+dd : dd;
mm = (mm < 10) ? "0"+mm : mm;
yyyy = (yyyy < 100) ? "20"+yyyy : yyyy;
var d_iso = new Date(yyyy+"-"+mm+"-"+dd+"T00:00:00.000Z").toJSON();
var iso = yyyy+"-"+mm+"-"+dd+"T00:00:00.000Z";
if(d_iso === iso)
return true;
else
return false;
}
console.log(validateDate(4, 2, 19)); // true
console.log(validateDate(31, 2, 19)); // false
console.log(validateDate(31, 4, 2019)); // false
console.log(validateDate(31, 3, 2019)); // true

Month range only should be within 9 months back from the selected month

I have two ranges for month and year.start and end range.
If I select end date june2016 start date it should be from the past 9 months.
If I select wrong I will get error message. I did but it is not working. Please help anyone.
http://jsfiddle.net/GUSN5/84/
Valid Condition:
Examples:
End Date :sep2016.
Start Date :Dec2015
Same month should be accept:
End Date :sep2016.
Start Date :sep2016
Invalid Condition:
Examples:
End Date :sep2016.
Start Date :oct2016
HTMl:
End date:
<select name="monthEnd" id="monthEnd" aria-required="" class="salary fll mr">
<option value="def">Month</option>
<option value="1">Jan</option>
<option value="2">Feb</option>
<option value="3">Mar</option>
<option value="4">Apr</option>
<option value="5">May</option>
<option value="6">Jun</option>
<option value="7">Jul</option>
<option value="8">Aug</option>
<option value="9">Sep</option>
<option value="10">Oct</option>
<option value="11">Nov</option>
<option value="12">Dec</option>
</select>
<select class="salary" aria-required="" id="yearEnd" name="yearEnd">
<option val="def">Year</option>
<option value="2016" selected="selected">2016</option>
<option value="2015">2015</option>
<option value="2014">2014</option>
<option value="2013">2013</option>
<option value="2012">2012</option>
</select>
Start Date:
<select name="monthStart" id="monthStart" aria-required="" class="salary fll mr">
<option value="def">Month</option>
<option value="1">Jan</option>
<option value="2">Feb</option>
<option value="3">Mar</option>
<option value="4">Apr</option>
<option value="5">May</option>
<option value="6">Jun</option>
<option value="7">Jul</option>
<option value="8">Aug</option>
<option value="9">Sep</option>
<option value="10">Oct</option>
<option value="11">Nov</option>
<option value="12">Dec</option>
</select>
<select class="salary" aria-required="" id="yearStart" name="yearStart" selected="selected">
<option selected="selected">Year</option>
<option value="2016">2016</option>
<option value="2015">2015</option>
<option value="2014">2014</option>
<option value="2013">2013</option>
<option value="2012">2012</option>
</select>
Javascript:
var $monthStart = $('#monthStart'),
$yearStart = $('#yearStart'),
$monthEnd = $('#monthEnd'),
$yearEnd = $('#yearEnd');
$(document).on('change','#monthEnd,#monthStart,#yearEnd,#yearStart', function() {
var startM = parseInt($monthStart.val()),
endM = parseInt($monthEnd.val()),
diffY = $yearEnd.val() - $yearStart.val(),
diffM = $monthEnd.val() - $monthStart.val();
if ((diffY == 0 && diffM < 0) ||(diffY == 0 && diffM >= 9) ||(diffY == 1 && diffM >= 9) || (diffY < 0) || (diffY > 1) || (diffY == 1 && diffM > -10)) {
alert("Selected range is not correct bcoz that range is not within 9 months from back");
} else {
alert("Selected range correct bcoz that range is within 9 months from back");
}
});
Try below code
$(document).ready(function () {
var $monthStart = $('#monthStart'),
$yearStart = $('#yearStart'),
$monthEnd = $('#monthEnd'),
$yearEnd = $('#yearEnd');
$(document).on('change', '#monthEnd,#monthStart,#yearEnd,#yearStart', function () {
if ($monthStart.val() != 'def' && $monthEnd.val() != 'def' && $yearStart.val() != 'def' && $yearEnd.val() != 'def') {
var startM = parseInt($monthStart.val()),
endM = parseInt($monthEnd.val()),
diffY = $yearEnd.val() - $yearStart.val(),
diffM = $monthEnd.val() - $monthStart.val();
if (validate(diffY, startM, endM)) {
alert("Selected range is not correct bcoz that range is not within 9 months from back");
}
else {
alert("Selected range correct bcoz that range is within 9 months from back");
}
}
});
function validate(diffY, startM, endM) {
var diffM = (endM + (diffY * 12)) - startM;
alert(endM + (diffY * 12));
alert(diffY);
alert(diffM);
if (diffM > 9 || diffM < 0)
return true;
else
return false;
}
});
and
set value for start year option like below
<option selected="selected" value="def">Year</option>
To simplify logic you can compare total number of months from AD. Also add validation that all fields set at the start (http://jsfiddle.net/unecL3yz/1/):
var $monthStart = $('#monthStart'),
$yearStart = $('#yearStart'),
$monthEnd = $('#monthEnd'),
$yearEnd = $('#yearEnd');
$(document).on('change','#monthEnd,#monthStart,#yearEnd,#yearStart', function() {
if([$yearStart,$yearEnd,$monthStart,$monthEnd].some(f => isNaN(f.val())))
return;
let diff = ($yearEnd.val()-$yearStart.val())*12 + $monthEnd.val()-$monthStart.val()
if(diff>=0 && diff<=9)
alert(`Selected range correct bcoz that range is within 9 months from back: ${diff}`);
else
alert(`Selected range is not correct bcoz that range is not within 9 months from back: ${diff}`);
});
Issue is need to check if range is correct once all four inputs are filled and need to convert $yearEnd.val() - $yearStart.val() to a int with parseInt().
$(document).on('change', '#monthEnd,#monthStart,#yearEnd,#yearStart', function() {
var $monthStart = $('#monthStart'),
$yearStart = $('#yearStart'),
$monthEnd = $('#monthEnd'),
$yearEnd = $('#yearEnd');
if ($monthEnd.val() && $yearEnd.val() && $monthStart.val() && $yearStart.val()) {
var diffY = parseInt($yearStart.val() - $yearEnd.val()),
diffM = parseInt($monthStart.val() - $monthEnd.val());
if ( (diffY === 0 && diffM >= -9 && diffM <= 0) || (diffY === -1 && diffM >= 3 && diffM <= 11) ) {
console.log('Date range is within 9 months.');
} else {
console.log('Date range is not within 9 months.');
this.value = "";
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
End date:
<select name="monthEnd" id="monthEnd">
<option value="">Month</option>
<option value="1">Jan</option>
<option value="2">Feb</option>
<option value="3">Mar</option>
<option value="4">Apr</option>
<option value="5">May</option>
<option value="6">Jun</option>
<option value="7">Jul</option>
<option value="8">Aug</option>
<option value="9">Sep</option>
<option value="10">Oct</option>
<option value="11">Nov</option>
<option value="12">Dec</option>
</select>
<select name="yearEnd" id="yearEnd">
<option value="">Year</option>
<option value="2016">2016</option>
<option value="2015">2015</option>
<option value="2014">2014</option>
<option value="2013">2013</option>
<option value="2012">2012</option>
</select>
<br/>
<br/> Start Date:
<select name="monthStart" id="monthStart">
<option value="">Month</option>
<option value="1">Jan</option>
<option value="2">Feb</option>
<option value="3">Mar</option>
<option value="4">Apr</option>
<option value="5">May</option>
<option value="6">Jun</option>
<option value="7">Jul</option>
<option value="8">Aug</option>
<option value="9">Sep</option>
<option value="10">Oct</option>
<option value="11">Nov</option>
<option value="12">Dec</option>
</select>
<select id="yearStart" name="yearStart">
<option value="">Year</option>
<option value="2016">2016</option>
<option value="2015">2015</option>
<option value="2014">2014</option>
<option value="2013">2013</option>
<option value="2012">2012</option>
</select>
Also I find it best to have the first option <option value="">Month</option> value set to blank (empty).

Having issues with a javascript for loop += decimal variable [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Hi guys I am building a for loop which basically generates a dynamic select options form.
Everything works fine until I try and use a decimal value as an incrementer.
for instance a normal loop would be this:
for(i =0; i <= 10; i++){
// do some code
}
The issue I am facing is that everything that is being put in is dynamic including the increment which may need to increment with decimal figures!
For instance it may need this:
for(i =0; i <= 10.5;i+= 1.5){
//do some code
}
Now the thing is that again everything is dynamic so the actual end code looks like this:
for(thei = 0; thei <= calchours; thei += +thetype){
}
Everything works 100% if the "thetype" is just 1, but as soon as its a 1.5 it only loops a few times before exiting.
Here is the Example code of what I am trying to do:
Example Html Code:
<select class="form-control" id="bookingtype" name="bookingtype">
<option value="1" selected="">Hourly Bookings</option>
<option value="1.5">1 Hour Bookings With 30 Minute Intervals</option>
</select>
<select class="form-control" id="timefrom" name="timefrom">
<option value="N/A" selected="">N/A</option>
<option value="24">00:00</option>
<option value="01">01:00</option>
<option value="02">02:00</option>
<option value="03">03:00</option>
<option value="04">04:00</option>
<option value="05">05:00</option>
<option value="06">06:00</option>
<option value="07">07:00</option>
<option value="08">08:00</option>
<option value="09" selected="selected">09:00</option>
<option value="10">10:00</option>
<option value="11">11:00</option>
<option value="12">12:00</option>
<option value="13">13:00</option>
<option value="14">14:00</option>
<option value="15">15:00</option>
<option value="16">16:00</option>
<option value="17">17:00</option>
<option value="18">18:00</option>
<option value="19">19:00</option>
<option value="20">20:00</option>
<option value="21">21:00</option>
<option value="22">22:00</option>
<option value="23">23:00</option>
</select>
<select class="form-control" id="timeto" name="timeto">
<option value="N/A" selected="">N/A</option>
<option value="24">00:00</option>
<option value="00.5">00:30</option>
<option value="01">01:00</option>
<option value="01.5">01:30</option>
<option value="02">02:00</option>
<option value="02.5">02:30</option>
<option value="03">03:00</option>
<option value="03.5">03:30</option>
<option value="04">04:00</option>
<option value="04.5">04:30</option>
<option value="05">05:00</option>
<option value="05.5">05:30</option>
<option value="06">06:00</option>
<option value="06.5">06:30</option>
<option value="07">07:00</option>
<option value="07.5">07:30</option>
<option value="08">08:00</option>
<option value="08.5">08:30</option>
<option value="09">09:00</option>
<option value="09.5">09:30</option>
<option value="10">10:00</option>
<option value="10.5">10:30</option>
<option value="11">11:00</option>
<option value="11.5">11:30</option>
<option value="12">12:00</option>
<option value="12.5">12:30</option>
<option value="13">13:00</option>
<option value="13.5">13:30</option>
<option value="14">14:00</option>
<option value="14.5">14:30</option>
<option value="15">15:00</option>
<option value="15.5">15:30</option>
<option value="16">16:00</option>
<option value="16.5">16:30</option>
<option value="17" selected="selected">17:00</option>
<option value="17.5">17:30</option>
<option value="18">18:00</option>
<option value="18.5">18:30</option>
<option value="19">19:00</option>
<option value="19.5">19:30</option>
<option value="20">20:00</option>
<option value="20.5">20:30</option>
<option value="21">21:00</option>
<option value="21.5">21:30</option>
<option value="22">22:00</option>
<option value="22.5">22:30</option>
<option value="23">23:00</option>
<option value="23.5">23:30</option>
</select>
<input id="dinnerswitch" type="checkbox" value="1">
<div id="dinnerhourdiv" class="form-group">
<label class="col-sm-3 control-label">Select Which Hour You Would Like To Have Off?</label>
<div class="col-sm-2" id="showdinnerhours"></div>
</div>
Example Javascript
jQuery(document).read(function(){
jQuery('#dinnerswitch').change(function(){
if(jQuery(this).is(':checked')) {
jQuery(this).val(1);
};
if(jQuery(this).is(':checked') == false) {
jQuery(this).val(0);
};
var dinnerid = jQuery('#dinnerswitch').val();
var thestart = jQuery('#timefrom').val();
var theend = jQuery('#timeto').val();
var thetype = jQuery('#bookingtype').val();
var thei = 0;
var doi = '';
var calchours = ((theend - thestart) / thetype);
var calstart = '';
var calend = '';
var enterhours = '';
var addingnumbers = 0;
for(thei = 0; thei <= calchours; thei+= +thetype){
calstart = +thestart + +thei;
if(calstart < 12){
calend = calstart + ' AM';
} else {
calend = calstart + ' PM';
}
calend = calend.replace('.5', ':30');
enterhours += '<option value="' + addingnumbers + '">' + calend + '</option>';
addingnumbers = +addingnumbers + 1;
}
if(dinnerid == 1){
jQuery('#showdinnerhours').html('<select class="form-control" name="dinnerhour" id="dinnerhour">' + enterhours + '</select>');
jQuery('#dinnerhourdiv').removeClass('hidden');
} else {
jQuery('#showdinnerhours').html('');
jQuery('#dinnerhourdiv').addClass('hidden');
}
});
});
Your logic does exactly what you told it to do!
When selecting "1 hour bookings with 30 minute intervals", and start as 9:00 and end as 17:00 your variables have the following values:
thestart = 09
theend = 17
thetype = 1.5
therefore
calchours = 5.333333 or ((17-9)/1.5)
Your loop starts at zero, continues until calchoursand increments by 1.5. Therefore the loop only runs 4 times, giving you entries in the dynamic select of 9:00, 10:30, 12 & 13:30.
This is entirely consistent with "maths", and I came to these conclusions through the magic of "debugging". Check the console: http://jsfiddle.net/7x82d66h/

Get the field value by label time field as below.

I want to get the Hour and minute value from below control by using there label
also I want to set the value to that control.
Using jQuery and javascript.
<td class="ms-dttimeinput" nowrap="nowrap">
<label for="ctl00_m_g_460bfeda_4d7a_4f5e_9587_9e0cd11d65ce_ff211_ctl00_ctl00_DateTimeField_DateTimeFieldDateHours" style="display:none">NEndTime Hours</label>
<select name="ctl00$m$g_460bfeda_4d7a_4f5e_9587_9e0cd11d65ce$ff211$ctl00$ctl00$DateTimeField$DateTimeFieldDateHours" id="ctl00_m_g_460bfeda_4d7a_4f5e_9587_9e0cd11d65ce_ff211_ctl00_ctl00_DateTimeField_DateTimeFieldDateHours">
<option selected="selected" value="00:">00:</option>
<option value="01:">01:</option>
<option value="21:">21:</option>
<option value="22:">22:</option>
<option value="23:">23:</option>
</select>
<label for="ctl00_m_g_460bfeda_4d7a_4f5e_9587_9e0cd11d65ce_ff211_ctl00_ctl00_DateTimeField_DateTimeFieldDateMinutes" style="display:none">NEndTime Minutes</label>
<select name="ctl00$m$g_460bfeda_4d7a_4f5e_9587_9e0cd11d65ce$ff211$ctl00$ctl00$DateTimeField$DateTimeFieldDateMinutes" id="ctl00_m_g_460bfeda_4d7a_4f5e_9587_9e0cd11d65ce_ff211_ctl00_ctl00_DateTimeField_DateTimeFieldDateMinutes">
<option selected="selected" value="00">00</option>
<option value="05">05</option>
<option value="10">10</option>
<option value="15">15</option>
<option value="20">20</option>
<option value="25">25</option>
<option value="30">30</option>
<option value="35">35</option>
<option value="40">40</option>
<option value="45">45</option>
<option value="50">50</option>
<option value="55">55</option>
</select></td>
Get the value for hr and min using the text in the label tags
var hr,min;
$(".ms-dttimeinput label").each(function() {
var lbl = $(this);
if(lbl.text() == "NEndTime Hours")
hr = lbl.next("select").val();
if(lbl.text() == "NEndTime Minutes")
min = lbl.next("select").val();
});
Set the value for hr and min using the text in the label tags
var hr = "01";
var min = "o5";
$(".ms-dttimeinput label").each(function() {
var lbl = $(this);
if(lbl.text() == "NEndTime Hours")
lbl.next("select").val(hr);
if(lbl.text() == "NEndTime Minutes")
lbl.next("select").val(min);
});
If there is only one widget on the page the more practical approach would be using the class name selector "ms-dttimeinput" with the descendent tag selector " select" and the nth child class ":nth-child()".
var hr = $(".ms-dttimeinput select:nth-child(1)").val();
var min = $(".ms-dttimeinput select:nth-child(2)").val();
$(".ms-dttimeinput select:nth-child(1)").val(hr);
$(".ms-dttimeinput select:nth-child(2)").val(min);

Javascript add textfield button doesn't work properly

I have made the following code
HTML:
<form method="post" id="myemailform" name="myemailform" action="form-to-email.php">
<div id="form_container">
<label class="description" for="pax">Number:</label>
<div>
<select class="select small" id="pax" name="pax">
<option value="" selected="selected"></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>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
<option value="31">31</option>
<option value="32">32</option>
<option value="33">33</option>
<option value="34">34</option>
<option value="35">35</option>
<option value="36">36</option>
<option value="37">37</option>
<option value="38">38</option>
<option value="39">39</option>
<option value="40">40</option>
</select>
</div>
<label class="description">ID:</label>
<input type='text' id="idpl" class="id-text-len" name='ids1' placeholder="ID #1">
<input class="btn btn-primary" type='button' id='btnMore' value='Add Ids'>
</form>
js:
jQuery(function ($) {
$('#btnMore').click(function () {
var form, fields, newField;
var e = document.getElementById("pax");
var strUser = e.options[e.selectedIndex].text;
form = $("#myemailform");
for (var i = 1; i < strUser; i++) {
fields = form.find("input[name^='ids']");
newField = $(fields[0]).clone();
newField.attr('name', 'ids' + (fields.length + 1));
newField.attr('placeholder', 'ID #' + (fields.length + 1));
newField.insertAfter(fields.last());
}
});
});
You can see the jsfiddle .
What i want is when i click on the button to add fields, not add more on the existing but new.
I mean e.g. first time i click 10 and then add, as a results i'll get 10 textfields. Then if i click 14 i don't want to get 10+14=24 textfields but 4 more, i want 14textfields.
I haven't made it up to do that. Please someone help me by code, in general i know why that's happening but i don't know how to solve that.
Try
jQuery(function($) {
var form = $("#myemailform");;
$('#btnMore').click(function() {
var fields, newField;
var opt = parseInt($('#pax').val());
var len = opt - $('.id-text-len').length;
if(len> 0){
for (var i = 0; i < len; i++) {
fields = form.find(".id-text-len");
newField = $(fields[0]).clone();
newField.attr('name', 'ids' + (fields.length + 1));
newField.attr('placeholder', 'ID #' + (fields.length + 1));
newField.val('');
newField.insertAfter(fields.last());
}
} else {
form.find(".id-text-len:gt("+ (opt - 1) +")").remove()
}
});
});
Demo: Fiddle
how about this
http://jsfiddle.net/7QUea/3/
i think this is the one you need
just one more line
$("input[name^='ids']").not("input[name='ids1']").remove();
jQuery(function($) {
$('#btnMore').click(function() {
$("input[name^='ids']").not("input[name='ids1']").remove();
var form, fields, newField;
var e = document.getElementById("pax");
var strUser = e.options[e.selectedIndex].text;
form = $("#myemailform");
for (var i = 1; i < strUser; i++) {
fields = form.find("input[name^='ids']");
newField = $(fields[0]).clone();
newField.attr('name', 'ids' + (fields.length + 1));
newField.attr('placeholder', 'ID #' + (fields.length + 1));
newField.insertAfter(fields.last());}
});
});
Changed a few things (now it is more jQuery styled):
jQuery(function ($) {
$('#btnMore').click(function () {
var strUser = $("#pax").val();
var form = $("#myemailform");
var fields = form.find("input[name^='ids']");
for (var i = 0; i < (strUser - fields.length); i++) {
var newField = $(fields[0]).clone();
newField.attr('name', 'ids' + (fields.length + 1 + i));
newField.attr('placeholder', 'ID #' + (fields.length + 1 + i));
form.find("input[name^='ids']").last().after(newField);
}
});
});
Check here: http://jsfiddle.net/7QUea/4/

Categories