I have a custom form-group for an online scheduler. I am trying to find the best approach for joining inputs together into one string for a time. I used jQuery's map function which seems to work pretty good. Am I going to have any issues with this approach on mobile devices or touch screens?
External JSFiddle
$('input, select').on('change', function() {
var userTime = $('.form-appointment-time select[name=form-hour], select[name=form-minute], input[name=time_format]:checked')
.map(function() {
return this.value;
}).get().join();
var userDate = userTime.replace(',', ':');
// For preview
$('.result').replaceWith('<p class="result">' + userDate + '</p>');
});
<link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<div class="form-group form-appointment-time">
<label class="col-sm-2 control-label">Preferred Time:</label>
<div class="col-sm-10">
<div class="form-inline">
<select class="form-control" name="form-hour">
<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>
</select>
<select class="form-control" name="form-minute">
<option value="00">00</option>
<option value="30">30</option>
</select>
<input name="time_format" id="time-am" type="radio" value="AM">
<label for="time-am">AM</label>
<input name="time_format" id="time-pm" type="radio" value="PM">
<label for="time-pm">PM</label>
</div>
</div>
</div>
<p class="result"></p>
You can combine, map, reduce, and join to format your time. You can use reduce to flatten the array, when you get to the point where you need a space.
I added the styling rules for the field as Виктор Щелкунов suggested.
var timeFields = [{
text: 'Hour',
value: 11
}, {
text: 'Minute',
value: 59
}, {
text: 'Second',
value: 59
}, {
text: 'Millisecond',
value: 999
}, {
text: 'Meridiem',
value: 'PM'
}];
function formatTime(items) {
return items.map(function(item) {
return item.value;
}).reduce(function(res, item, idx, arr) {
return (idx !== 4 ? res : [res.join(':')]).concat([item]);
}, [])
.join(' ');
}
document.body.innerHTML = formatTime(timeFields);
In Action
I modified the formatTime function so that you can pass in the index where there should be a space.
$('input, select').on('change', function() {
var userDate = formatTime($('.form-appointment-time select[name=form-hour], select[name=form-minute], input[name=time_format]:checked').get(), 2);
// For preview
$('.result').replaceWith('<p class="result">' + userDate + '</p>');
});
function formatTime(items, spaceIndex) {
return items.map(function(item) {
return item.value;
}).reduce(function(res, item, idx, arr) {
return (idx !== spaceIndex ? res : [res.join(':')]).concat([item]);
}, [])
.join(' ');
}
select,input{
width: auto !important;
display: inline-block !important;
}
<link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<div class="form-group form-appointment-time">
<label class="col-sm-2 control-label">Preferred Time:</label>
<div class="col-sm-10">
<div class="form-inline">
<select class="form-control" name="form-hour">
<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>
</select>
<select class="form-control" name="form-minute">
<option value="00">00</option>
<option value="30">30</option>
</select>
<input name="time_format" id="time-am" type="radio" value="AM">
<label for="time-am">AM</label>
<input name="time_format" id="time-pm" type="radio" value="PM">
<label for="time-pm">PM</label>
</div>
</div>
</div>
<p class="result"></p>
Another Approach
You can also use an array of stop-points to control when to join values in the array. Array.prototype.shift() is a very useful method. It will remove the first item in an array for immediate use. The array will automatically be updated.
Array.multiJoin = function(arr, stops) {
return arr.reduce(function(res, item, idx) {
return (
(stops.length > 1 && idx > stops[1][0]) ||
(stops.length === 1 && idx === stops[0][0]) ?
[res.join(stops.shift()[1])] : res
).concat([item]);
}, [])
.join(stops.length > 0 ? stops[0][1] : '');
}
var timeFields = [
{ text: 'Hour', value: 11 },
{ text: 'Minute', value: 59 },
{ text: 'Second', value: 59 },
{ text: 'Millisecond', value: 999 },
{ text: 'Meridiem', value: 'PM' }
];
var stops = [
[0, ':'],
[2, '.'],
[3, ' ']
];
function formatTime(items, stops) {
return Array.multiJoin(
items.map(function(item) {
return item.value;
}), stops);
}
document.body.innerHTML = formatTime(timeFields, stops);
In your example, an a mobile device, the select and input elements have the display css property set to "block", and the width property set to "100%". Ensure that these elements always "width: auto" and "display:inline-block". See this jsfiddle on a mobile device.
select,input{
width: auto !important;
display: inline-block !important;
}
You may want to store the references to elements for reuse later on as scanning the DOM over and over for the same element is expensive and unnecessary. So, your code could be re-written with as minimal and slightly cleaner code as the following.
//Store the container
var $wrapper = $('.form-appointment-time');
//Store the input elements. This may be useful if at all you wanted to change attributes, such as name etc.
var inputs = [
"select[name='form-hour']",
"select[name='form-minute']",
"input[name='time_format']:checked"
];
//Ensures that only the inputs, selects within the container are considered.
$wrapper.on('change', 'input, select', function() {
var userTime = $wrapper.find(inputs.join(', '))
.map(function() {
return this.value;
}).get().join(":");
var userDate = userTime.replace(/:(?!.*:)/g, " ");
// For preview
$('.result').replaceWith('<p class="result">' + userDate + '</p>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group form-appointment-time">
<label class="col-sm-2 control-label">Preferred Time:</label>
<div class="col-sm-10">
<div class="form-inline">
<select class="form-control" name="form-hour">
<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>
</select>
<select class="form-control" name="form-minute">
<option value="00">00</option>
<option value="30">30</option>
</select>
<input name="time_format" id="time-am" type="radio" value="AM">
<label for="time-am">AM</label>
<input name="time_format" id="time-pm" type="radio" value="PM">
<label for="time-pm">PM</label>
</div>
</div>
</div>
<p class="result"></p>
Related
I am trying to making a list, in which it calculate the sum of select numbers.
There are actually over 300 items, so I limited to 6 here.
Generally, the "Image with name" adding, Change Language, Calculations all works.
I also tried the "arrange buttons" in small scale, for which it also works.
But when I add the "rearrange" buttons for the list, the page just keep refreshing back to its original way.
Is there a way to do the rearrange DIV trick?
(By the way, this seems to be working on Firefox, Chrome and Safari, but just never works on IE/Edge)
let imgList = [{
name: 30001,
file: 'icon/30001.gif',
jpName = 'ア',
engName = 'alpha'
},
{
name: 30002,
file: 'icon/30002.jpg',
jpName = 'イ',
engName = 'beta'
},
(name: 40001, file: 'icon/40001.gif', jpName = 'ウ',
engName = 'gamma'
},
{
name: 41002,
file: 'icon/41002.jpg',
jpName = 'エ',
engName = 'delta'
},
{
name: 50301,
file: 'icon/50301.jpg',
jpName = 'オ',
engName = 'mu'
},
{
name: 50401,
file: 'icon/50401.jpg',
jpName = 'ン',
engName = 'nu'
}
];
//Language Controler
let control = [{
name: 'jp',
title: '計算',
ans: '答え'
},
{
name: 'eng',
title: 'Calculations',
ans: 'Answer'
}
]
//Array Lists
let ArrayOne = ['test30001', 'test30002', 'test40001', 'test41002', 'test50301', 'test50401'];
let ArrayTwo = ['test50301', 'test50401', 'test40001', 'test41002', 'test30001', 'test30002'];
let ArrayThree = ['test30001', 'test40001', 'test50301', 'test50401', 'test30002', 'test41002'];
//Give images and name
function goImage(arr) {
let x = imgList.findIndex(num => num['name'] === arr);
document.getElementById('art' + arr).innerHTML = '<img src="' + imgList[x].file + '"><br>' + imgList[x][language + 'Name'];
}
//Change page language
function placeAll() {
let tb = control.findIndex(lang => lang['name'] === language);
document.getElementById('title').innerHTML = control[tb].title;
document.getElementById('totalName').innerHTML = control[tb].ans;
imgList.forEach(nameFile => {
goImage(nameFile.name)
});
}
//when select other languages
let language = 'jp';
function handleLang(myRadio) {
language = myRadio.value;
placeAll();
}
//amount calculations
function calculate() {
var calValue = 0;
countThese.each(function() {
calValue += +$(this).val();
})
localStorage.setItem($(this).attr('id'), $(this).val());
let allRate = imgList.length * 10;
document.getElementById('totalAm').innerHTML = ((calValue / allRate) * 100).toFixed(2) + '%';
}
let countThese = $('#testBox:input').click(calculate);
//rearrange div boxes
function ArrayOne() {
$('#testBox div').each(function() {
if ($.inArray($(this).attr('id'), ArrayOne) == -1) {
$('#testBox').append($('#' + $(this).attr('id')));
}
});
};
function ArrayTwo() {
$('#testBox div').each(function() {
if ($.inArray($(this).attr('id'), ArrayTwo) == -1) {
$('#testBox').append($('#' + $(this).attr('id')));
}
});
};
function ArrayThree() {
$('#testBox div').each(function() {
if ($.inArray($(this).attr('id'), ArrayThree) == -1) {
$('#testBox').append($('#' + $(this).attr('id')));
}
});
};
<div id='title'></div>
<form id="calcul">
<div class="container" id="testBox">
<div class="tryBox" id="test30001">
<div id="art30001" class="star3">
</div>
<div id="ca30001" class="calLV3">
<select id="t30001" class="sLV3">
<option value="0">0</option>
<option value="0">1</option>
<option value="0">2</option>
</select>
</div>
</div>
<div class="tryBox" id="test30002">
<div id="art30002" class="star3">
</div>
<div id="ca30002" class="calLV3">
<select id="t30002" class="sLV3">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
</div>
<div class="tryBox" id="test40001">
<div id="art40001" class="star4">
</div>
<div id="ca40001" class="calLV4">
<select id="t40001" class="sLV4">
<option value="0">0</option>
<option value="2">2</option>
<option value="4">4</option>
</select>
</div>
</div>
<div class="tryBox" id="test41002">
<div id="art41002" class="star4">
</div>
<div id="ca41002" class="calLV4">
<select id="t41002" class="sLV4">
<option value="0">0</option>
<option value="2">2</option>
<option value="4">4</option>
</select>
</div>
</div>
<div class="tryBox" id="test50301">
<div id="art50301" class="star5">
</div>
<div id="ca50301" class="calLV5">
<select id="t50301" class="sLV5">
<option value="0">0</option>
<option value="1">1</option>
<option value="3">3</option>
<option value="5">5</option>
<option value="7">7</option>
</select>
</div>
</div>
<div class="tryBox" id="test50401">
<div id="art50401" class="star5">
</div>
<div id="ca50401" class="calLV5">
<select id="t50401" class="sLV5">
<option value="0">0</option>
<option value="1">1</option>
<option value="3">3</option>
<option value="5">5</option>
<option value="7">7</option>
</select>
</div>
</div>
</div>
</form>
<div id='button1'>
<button onclick="ArrayOne()">WAY1</button>
<button onclick="ArrayTwo()">WAY2</button>
<button onclick="ArrayThree()">WAY3</button>
</div>
<div id='lang'>
<input type="radio" id="jp" name="lang" value="jp" onchange="handleLang(this)" checked>
<label for="jp">日本語</label>
<input type="radio" id="eng" name="lang" value="eng" onchange="handleLang(this)">
<label for="eng">English</label>
</div>
<div class="answer">
<div class="totalName" id="totalName"></div>
<div class="totalAm" id="totalAm"></div>
</div>
<script src="script.js"></script>
There are some syntax problems, like = in your object map declarations, redeclaration of ArrayOne as a function, and a ( in your object map.
You are iterating over the HTML elements in the order that they appear, and searching the array each time as a filter. If you want them to be in the order that the array indicates, you should be iterating in order over the array.
Or you have to account for the array index while you append, and insert them in the right position, which is more involved. The easiest would be to use CSS flex and order: (number)
Also, ids should be unique to the document, so searching into #testBox and then finding the id that you want should not be necessary. You should be able to use the #id selector directly. I have kept the selectors as $('#testBox div#'+id), just to match your original code, but it should really be just $('#'+id') or document.getElementById(id)
let imgList = [{
name: 30001,
file: 'icon/30001.gif',
jpName: 'ア',
engName: 'alpha'
},
{
name: 30002,
file: 'icon/30002.jpg',
jpName: 'イ',
engName: 'beta'
},
{name: 40001, file: 'icon/40001.gif', jpName: 'ウ',
engName: 'gamma'
},
{
name: 41002,
file: 'icon/41002.jpg',
jpName: 'エ',
engName: 'delta'
},
{
name: 50301,
file: 'icon/50301.jpg',
jpName: 'オ',
engName: 'mu'
},
{
name: 50401,
file: 'icon/50401.jpg',
jpName: 'ン',
engName: 'nu'
}
];
//Language Controler
let control = [{
name: 'jp',
title: '計算',
ans: '答え'
},
{
name: 'eng',
title: 'Calculations',
ans: 'Answer'
}
]
//Array Lists
let ArrayOne = ['test30001', 'test30002', 'test40001', 'test41002', 'test50301', 'test50401'];
let ArrayTwo = ['test50301', 'test50401', 'test40001', 'test41002', 'test30001', 'test30002'];
let ArrayThree = ['test30001', 'test40001', 'test50301', 'test50401', 'test30002', 'test41002'];
//Give images and name
function goImage(arr) {
let x = imgList.findIndex(num => num['name'] === arr);
document.getElementById('art' + arr).innerHTML = '<img src="' + imgList[x].file + '"><br>' + imgList[x][language + 'Name'];
}
//Change page language
function placeAll() {
let tb = control.findIndex(lang => lang['name'] === language);
document.getElementById('title').innerHTML = control[tb].title;
document.getElementById('totalName').innerHTML = control[tb].ans;
imgList.forEach(nameFile => {
goImage(nameFile.name)
});
}
//when select other languages
let language = 'jp';
function handleLang(myRadio) {
language = myRadio.value;
placeAll();
}
//amount calculations
function calculate() {
var calValue = 0;
countThese.each(function() {
calValue += +$(this).val();
})
localStorage.setItem($(this).attr('id'), $(this).val());
let allRate = imgList.length * 10;
document.getElementById('totalAm').innerHTML = ((calValue / allRate) * 100).toFixed(2) + '%';
}
let countThese = $('#testBox:input').click(calculate);
//rearrange div boxes
function ArrayOne1() {
$(ArrayOne).each(function() {
$('#testBox').append(
$('#testBox div#'+this)
);
});
/* $('#testBox div').each(function() {
if ($.inArray($(this).attr('id'), ArrayOne) == -1) {
$('#testBox').append($('#' + $(this).attr('id')));
}
});*/
};
function ArrayTwo1() {
$(ArrayTwo).each(function() {
$('#testBox').append(
$('#testBox div#'+this)
);
});
/*
$('#testBox div').each(function() {
if ($.inArray($(this).attr('id'), ArrayTwo) == -1) {
$('#testBox').append($('#' + $(this).attr('id')));
}
});*/
};
function ArrayThree1() {
$(ArrayThree).each(function() {
$('#testBox').append(
$('#testBox div#'+this)
);
});
/* $('#testBox div').each(function() {
if ($.inArray($(this).attr('id'), ArrayThree) == -1) {
$('#testBox').append($('#' + $(this).attr('id')));
}
});*/
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='title'></div>
<form id="calcul">
<div class="container" id="testBox">
<div class="tryBox" id="test30001">
<div id="art30001" class="star3">
</div>
<div id="ca30001" class="calLV3">
<select id="t30001" class="sLV3">
<option value="0">0</option>
<option value="0">1</option>
<option value="0">2</option>
</select>
</div>
</div>
<div class="tryBox" id="test30002">
<div id="art30002" class="star3">
</div>
<div id="ca30002" class="calLV3">
<select id="t30002" class="sLV3">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
</div>
<div class="tryBox" id="test40001">
<div id="art40001" class="star4">
</div>
<div id="ca40001" class="calLV4">
<select id="t40001" class="sLV4">
<option value="0">0</option>
<option value="2">2</option>
<option value="4">4</option>
</select>
</div>
</div>
<div class="tryBox" id="test41002">
<div id="art41002" class="star4">
</div>
<div id="ca41002" class="calLV4">
<select id="t41002" class="sLV4">
<option value="0">0</option>
<option value="2">2</option>
<option value="4">4</option>
</select>
</div>
</div>
<div class="tryBox" id="test50301">
<div id="art50301" class="star5">
</div>
<div id="ca50301" class="calLV5">
<select id="t50301" class="sLV5">
<option value="0">0</option>
<option value="1">1</option>
<option value="3">3</option>
<option value="5">5</option>
<option value="7">7</option>
</select>
</div>
</div>
<div class="tryBox" id="test50401">
<div id="art50401" class="star5">
</div>
<div id="ca50401" class="calLV5">
<select id="t50401" class="sLV5">
<option value="0">0</option>
<option value="1">1</option>
<option value="3">3</option>
<option value="5">5</option>
<option value="7">7</option>
</select>
</div>
</div>
</div>
</form>
<div id='button1'>
<button onclick="ArrayOne1()">WAY1</button>
<button onclick="ArrayTwo1()">WAY2</button>
<button onclick="ArrayThree1()">WAY3</button>
</div>
<div id='lang'>
<input type="radio" id="jp" name="lang" value="jp" onchange="handleLang(this)" checked>
<label for="jp">日本語</label>
<input type="radio" id="eng" name="lang" value="eng" onchange="handleLang(this)">
<label for="eng">English</label>
</div>
<div class="answer">
<div class="totalName" id="totalName"></div>
<div class="totalAm" id="totalAm"></div>
</div>
<script src="script.js"></script>
I am creating a web site. In this web site I have created a form. So , there are 2 dropdown menus like below.
I want to limit the number of adults and children to 9. One can select i.e. 4 adults and 0 to 5 children, or 6 adults and 0-3 children, but never more than 9 in total.
The code I tried out so far only worked for Adults , not for the Total ( Adults + Children ). But , it's not compulsory to select a value to the children menu. If th user wants, he can keep it as 0.
How can I do this ??
Here is the Jquery part I tried out:
<script type="text/javascript">
$(document).ready(function () {
var adults = parseFloat($('#adults').val());
var children = parseFloat($('#children').val());
var infants = $('#infants').val();
var Total = adults + children;
$('#adults').change(function() {
if (this.value > 8) {// check against the value of the adults drop down
$("#children").prop('disabled', true);
} else {
$("#children").prop('disabled', false); // probably need to re-enable it
}
});
});
</script>
Here are HTML Dropdown view.
<form class="form-horizontal" method="POST" action="#" enctype="multipart/form-data" id="signupForm">
<div class="col-md-4 col-sm-12 hero-feature">
<!-- Start Of The Col Class -->
Adults :
<select name="adults" class="form-control" id="adults">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select> <br>
</div>
<div class="col-md-4 col-sm-12 hero-feature">
<!-- Start Of The Col Class -->
Children :
<select name="children" class="form-control" id="children">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select> <br>
</div>
Search Flight Data
</form>
Below snippet might help you.
var totalAdultChild = 9;
$('#adults').change(function() {
var adultValue = this.value;
if (this.value > 8) {
$("#children").prop('disabled', true);
} else {
$("#children").prop('disabled', false);
$('#children option').each(function(index,element){
if((totalAdultChild-adultValue)<this.value){
$(this).hide();
} else {
$(this).show();
}
});
}
});
Currently I am using the following code
<form method="POST" id="form3" onSubmit="return false;" data-parsley-validate="true" v-on:submit="invSubmit($event);">
<h4 class="info-text">Give your Inventory and Work Hours ? </h4>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label>Working Hours :</label>
<div v-for="value in day" class="checkboxFour">
<input type="checkbox" id="need" value="value.val" v-model="value.selected" style="width: 10%!important;">
<label for="need" style=" width: 30%!important;">{{value.name}}</label>
<select v-model="value.from" class="select-style" v-bind:class="{required: isRequired}" required="">From
<option value="08:00">08.00</option>
<option value="09:00">09.00</option>
<option value="10:00">10.00</option>
<option value="11:00">11.00</option>
<option value="12:00">12.00</option>
<option value="13:00">13.00</option>
<option value="14:00">14.00</option>
<option value="15:00">15.00</option>
<option value="16:00">16.00</option>
<option value="17:00">17.00</option>
<option value="18:00">18.00</option>
<option value="19:00">19.00</option>
<option value="20:00">20.00</option>
<option value="21:00">21.00</option>
<option value="22:00">22.00</option>
<option value="23:00">23.00</option>
<option value="00:00">00.00</option>
<option value="01:00">01.00</option>
<option value="02:00">02.00</option>
<option value="03:00">03.00</option>
<option value="04:00">04.00</option>
<option value="05:00">05.00</option>
<option value="06:00">06.00</option>
<option value="07:00">07.00</option>
</select>
<select v-model="value.to" class="select-style" required="">To
<option value="17:00">17.00</option>
<option value="18:00">18.00</option>
<option value="19:00">19.00</option>
<option value="20:00">20.00</option>
<option value="21:00">21.00</option>
<option value="22:00">22.00</option>
<option value="23:00">23.00</option>
<option value="00:00">00.00</option>
<option value="01:00">01.00</option>
<option value="02:00">02.00</option>
<option value="03:00">03.00</option>
<option value="04:00">04.00</option>
<option value="05:00">05.00</option>
<option value="06:00">06.00</option>
<option value="07:00">07.00</option>
<option value="08:00">08.00</option>
<option value="09:00">09.00</option>
<option value="10:00">10.00</option>
<option value="11:00">11.00</option>
<option value="12:00">12.00</option>
<option value="13:00">13.00</option>
<option value="14:00">14.00</option>
<option value="15:00">15.00</option>
<option value="16:00">16.00</option>
</select>
<br>
</div>
</div>
</div>
<div class="wizard-footer">
<div class="pull-right">
<button type="submit" class='btn btn-next btn-primary' name='next' value='Next'>Next</button>
</div>
</div>
</div></form>
When I do this way I need to select working hours for each checkbox I am using. This is time consuming. I need to firstly choose a working hour and automatically choose that working hour for the checkboxes I am choosing. If I need to change a particular time for a checkbox, I need to do that too. How Can I able to achieve the same.
My vue js code is
submitBox = new Vue({
el: "#submitBox",
data: {
data: [],
day:[
{name:"Sunday",val:1},
{name:"Monday",val:2},
{name:"Tuesday",val:3},
{name:"Wednesday",val:4},
{name:"Thursday",val:5},
{name:"Friday",val:6},
{name:"Saturday",val:7}
],
string:'',
},
methods: {
invSubmit: function(e) {
var arr = [];
this.day.map(function(v,i) {
console.log(v.selected == true,);
if(v.selected == true)
{
arr.push(v.val+'&'+v.from+'&'+v.to);
}
});
this.string = arr.join(',');
var vm = this;
data = {};
data['inv'] = this.inv.join(',');
data['wrk_list'] = this.string;
data['pid'] = this.pid;
data['auth-token'] = this.authType;
$.ajax({
url: 'http://127.0.0.1:8000/alpha/add/post/inv_whr/',
data: data,
type: "POST",
dataType: 'json',
success: function(e) {
if (e.status)
{
$("#alertModal").modal('show');
$(".alert").removeClass("hidden").html("Your data has been successfully recorded");
}
else {
vm.response = e;
alert("Registration Failed")
}
}
});
return false;
},
}
I need to pass the data in the following format v.val+'&'+v.from+'&'+v.to. I t is been done as the above code.
How can I able to select a working hour first and then choose the days. If I need to change a workhour for a particular day, I need to do that too.
Please help me to have a solution. I am weak in js. This is the first time I am doing a project. Please help me to obtain a solution.
I'm a newbie and find very difficult to read and understand complex javascript from other's work.
I would like to ask some help in making a simplified jquery for me to use rather than using the complex code which I don't really understand.
First: this is a 5 step form consist of gender, first name, dob, email and password. There are validations in every steps.
See the complex code:
<script>
$(document).ready(function () {
var Fist = {
config: {
stepsSelector: $(".steps"),
nextSelector: $(".myButton"),
errorSelector: $(".error"),
indSelector: $(".steps-ind"),
form: "",
cur_step: 1,
max_step: 1,
offset: 278,
errorString: "This field is required",
clickEvent: "touchstart"
},
run: function(e) {
this.config.form = e;
var t = this;
var n = $(".regform").width();
t.config.offset = n;
if (typeof document.body.ontouchstart === "undefined") {
t.config.clickEvent = "click"
}
t.config.indSelector.find(".step-ind" + t.config.cur_step).addClass("step-ind-active");
t.config.nextSelector.on(t.config.clickEvent, function() {
t.process()
});
t.config.form.find("input").on("keypress", function(e) {
var n = e.keyCode ? e.keyCode : e.which;
if (n === 13) {
t.process()
}
});
t.config.indSelector.find("div").on(t.config.clickEvent, function() {
t.gotoStep($(this))
})
},
indicateStep: function(e) {
var t = this;
t.config.indSelector.find("div").removeClass("step-ind-active");
t.config.indSelector.find(".step-ind" + e).addClass("step-ind-active");
setTimeout(function() { $('.step'+e+' input, .step'+e+' select').focus() }, 500);
},
animateStep: function(e) {
var t = this;
t.config.stepsSelector.css({
transform: "translateX(-" + (e - 1) * t.config.offset + "px)"
}, function() {
t.config.form.find(".step" + e).find("input").focus()
})
},
process: function() {
var e = this;
var t = e.config.form.find(".step" + e.config.cur_step).find("input,select");
var n = false;
t.each(function() {
if (!e.validate($(this))) {
n = true
}
});
if (!n) {
e.config.cur_step++;
if (e.config.cur_step === 6) {
e.config.form.submit()
} else {
e.config.max_step = e.config.cur_step;
e.animateStep(e.config.cur_step);
e.indicateStep(e.config.cur_step);
if (e.config.cur_step === 5) {
e.config.nextSelector.val("Submit")
}
}
}
},
gotoStep: function(e) {
var t = e.text();
var n = this;
if (t < n.config.max_step) {
n.animateStep(t);
n.indicateStep(t);
n.config.cur_step = t;
if (t === 5) {
n.config.nextSelector.val("Submit")
} else {
n.config.nextSelector.val("Next")
}
} else {
n.process()
}
},
validate: function(e) {
var t = this;
t.config.errorSelector.hide();
e.removeClass("error-item");
var n = false;
if ($.trim(e.val()) === "") {
n = true;
t.config.errorString = "This field is required"
}
if (e.attr("name") === "email" && !t.validateEmail(e.val())) {
n = true;
t.config.errorString = "Invalid email address"
}
if (e.attr("name") === "firstname" && !t.validateName(e.val())) {
n = true;
t.config.errorString = "Invalid name"
}
if (n) {
t.config.errorSelector.empty().append(t.config.errorString).fadeIn("fast");
e.addClass("error-item");
return false
}
return true
},
validateEmail: function(e) {
var t = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return t.test(e)
},
validateInt: function(e) {
var t = /^\d{1,}$/;
return t.test(e)
},
validateName: function(e) {
var t = /^\w+(\s)?\w+(\s)?(\w+)?$/;
return t.test(e)
}
}
Fist.run($("#regform"));
});
Here is my HTML:
<div class="regform">
<div class="form-wrapper">
<form id="regform" method="post" action="http://www.test.com/signup">
<div class="steps step1">
<label>Your Gender?</label>
<div name="gender">
<div class="man-btn color" value="1">
<span>Man</span>
<div class="man" >
<i class="fa fa-male" aria-hidden="true"></i>
</div>
</div>
<div class="woman-btn" value="2">
<span>Woman</span>
<div class="woman">
<i class="fa fa-female" aria-hidden="true"></i>
</div>
</div>
</div>
</div>
<div class="steps step2">
<label>First Name:</label>
<input type="text" name="firstname">
</div>
<div class="steps step3">
<label>What is Your Date of Birth?</label>
<select name="dobday" id="dobday" class="required">
<option value="">Day</option>
<option value="1">01</option>
<option value="2">02</option>
<option value="3">03</option>
<option value="4">04</option>
<option value="5">05</option>
<option value="6">06</option>
<option value="7">07</option>
<option value="8">08</option>
<option value="9">09</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" class="required">
<option value="">Month</option>
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
<select name="dobyear" id="dobyear" class="required">
<option value="">Year</option>
<?php for($x=date("Y") - 18; $x >= 1918; $x--): ?>
<option value="<?php echo $x; ?>"><?php echo $x; ?></option>
<?php endfor; ?>
</select>
</div>
<div class="steps step4">
<label>Email:</label>
<input type="email" pattern="[^ #]*#[^ #]*" name="email">
</div>
<div class="steps step5">
<label>Password:</label>
<input type="password" name="password">
</div>
<div class="error">This field is required</div>
</form>
</div>
<div class="submit">
<input type="button" class="myButton" value="Next">
</div>
<div class="steps-ind">
<div class="step-ind1">1</div>
<div class="step-ind2">2</div>
<div class="step-ind3">3</div>
<div class="step-ind4">4</div>
<div class="step-ind5">5</div>
</div>
Please help me. Thank you so much for your help!
It's simple enough to add a new button! You could either change the gender to a select dropdown or you could add a new div like this:
<div class="bro-btn" value="3">
<span>Bro</span>
<div class="bro">
<i class="fa fa-bro" aria-hidden="true"></i>
</div>
</div>
Few things you have to note: The fa fa-bro is a reference to a class in your CSS that adds an icon corresponding to whatever gender is selected. If you were to add new buttons like above, you would have to find an icon that matches from Font Awesome.
I'm creating a quote generator, and I have a product field that's cloneable.
Each option in the select tag has a value, but there is a quantity next to the product, so that the user can select a product and how many they want.
The field is also clone-able so that the user can have multiple products each with their own quantities.
I need to take the quantity for each row, multiply it by the value of the option and add all the rows together to give a total.
This is what I have so far
HTML
<select class="form-control onChangePrice add product" name="Product">
<option value="">Select...</option>
<option value="3300">Product 1</option>
<option value="4500">Product 2</option>
<option value="6000">Product 3</option>
<option value="8000">Product 4</option>
</select>
<div class="col-lg-3 col-md-3 col-sm-3">
<input class="form-control onChangePrice productQuantity" type="number" name="ProductQuantity" value="1">
</div>
Javascript
$(".onChangePrice").change(function(){
var productTotal = 0;
$('.product').each(function(){
if (this.value != "") {
productEachTotal = this.value * $(".productQuantity").value;
productTotal += parseFloat(productEachTotal);
};
});
console.log(productTotal);
});
But its just returning NaN.
Any help would be appreciated!
Thanks
You need to use .val() to get the value.
$(".onChangePrice").change(function(){
var productTotal = 0;
$('.product').each(function(){
if (this.value != "") {
productEachTotal = this.value * parseInt($(".productQuantity").val());
productTotal += parseFloat(productEachTotal);
};
});
console.log(productTotal);
});
Try this one:
function calculateRowTotals(rowSelector, productSelector, quanitySelector) {
let rows = [].slice.call(document.querySelectorAll(rowSelector));
return rows.map(function(rowElement) {
var product = rowElement.querySelector(productSelector);
var quantity = rowElement.querySelector(quanitySelector);
if(!quantity || !product) return 0;
return parseFloat(product.value || 0) * Math.abs(parseFloat(quantity.value || 0));
});
}
function calculateTotal(rowSelector, productSelector, quanitySelector) {
return calculateRowTotals(rowSelector, productSelector, quanitySelector).reduce(function(total, rowTotal) {
return total + rowTotal;
}, 0);
}
// demo code
[].slice.call(document.querySelectorAll('.onChangePrice')).forEach(function(element) {
element.addEventListener('change', function(e) {
console.log('rows total: ', calculateRowTotals('.row', '.product', '.productQuantity'));
console.log('total: ', calculateTotal('.row', '.product', '.productQuantity'));
});
});
console.log(calculateTotal('.row', '.product', '.productQuanity'));
<div class="row">
<select class="form-control onChangePrice add product" name="Product">
<option value="">Select...</option>
<option value="3300">Product 1</option>
<option value="4500">Product 2</option>
<option value="6000">Product 3</option>
<option value="8000">Product 4</option>
</select>
<div class="col-lg-3 col-md-3 col-sm-3">
<input class="form-control onChangePrice productQuantity" type="number" name="ProductQuantity" value="1">
</div>
</div>
<div class="row">
<select class="form-control onChangePrice add product" name="Product">
<option value="">Select...</option>
<option value="3300">Product 1</option>
<option value="4500">Product 2</option>
<option value="6000">Product 3</option>
<option value="8000">Product 4</option>
</select>
<div class="col-lg-3 col-md-3 col-sm-3">
<input class="form-control onChangePrice productQuantity" type="number" name="ProductQuantity" value="1">
</div>
</div>