How to rearrange div boxes with js written children, following given array? - javascript

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>

Related

function needs to wait until select tag's value selected

I have a function in my main.js needs to wait until some options selected on select tag. According to that, I will update the element. I tried to do it with addlistenerevent, but I could not succeed it. Any suggestions? Am I doing wrong?
var test = function() {
const langOptions = {
dummy: 0,
one: 5,
two: 8,
three: 2
};
var unit_1 = 1;
var selectSource ="";
var selectTarget = "";
var section = document.getElementById("unit");
var span_1 = '<span>Unit : </span>';
section.insertAdjacentHTML("beforeend", span_1);
var span_2 = '<span id= "span_2">' + unit_1 +'</span>';
section.insertAdjacentHTML("beforeend", span_2);
document.getElementById('source-lang').addEventListener('change', function() {
selectSource = $('source-lang').find('select').val();
for (const key of Object.keys(langOptions)) {
if (key === selectSource || key === selectTarget) { unitPrice *= langOptions[key];}
}
var element = document.getElementById('span_2').innerHTML = unit_1;
});
};
test();
<div id="langs">
<section class="container">
<div class="dropdown">
<select id="source-lang" style="background-color:#5e3080" name="source-lang">
<option value="">Select</option>
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
</select>
</div>
<div class="dropdown">
<select id ="target-lang" style="background-color:#5e3080" name="target-lang">
<option value="">Select</option>
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
</select>
</div>
<div class="dropdown">
<div id="unit"></div>
</div>
</section>
</div>
I think that what you are looking for, is the onchange Event
function selectOne() {
const id = 'selectOne';
console.log(id, document.getElementById(id).value);
}
document.getElementById('selectTwo').addEventListener("change", function() {
console.log(this.id, this.value)
});
<p>Select One</p>
<select id="selectOne" type="text" onchange="selectOne()">
<option value=1>1</option>
<option value=2>2</option>
<option value=3>3</option>
</select>
<!-- Or using addEventListener -->
<p>Select Two</p>
<select id="selectTwo" type="text">
<option value=a>a</option>
<option value=b>b</option>
<option value=c>c</option>
</select>
Use onchange Event
<select id="source-lang" style="background-color:#5e3080" name="source-lang" onchange="test()">
<select id ="target-lang" style="background-color:#5e3080" name="target-lang" onchange="test()">

jQuery How To Add Form Validation Using 5-step Sliding Form

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.

Adding clone element values with quantities

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>

Product Filtering PHP

Hello guys I'm doing a product filtering and I don't know how could I achieve it.
I used Javascript by getting the value of the selected values then alert it but the problem is that how could I display it also how can I remove the categories selected by clicking the x button. Here the sample page. Thank you very much for your help.
Here is my script code:
<script>
jQuery("#filter").val()
jQuery(function(){
jQuery( ".product-line" ).each(function( index ) {
var url = '<?php echo $upload_url; ?>';
var desc_id = jQuery(this).eq(0).find('.prod-desc').attr('id');
if(desc_id){
var file_url = url + desc_id + '/description.html';
jQuery('#'+desc_id).eq(0).load( file_url );
}
});
jQuery("#brand,#screen_size,#cpu,#memory,#price").change(function() {
        var brand = jQuery("#brand").val();
var screen_size = jQuery("#screen_size").val();
var cpu = jQuery("#cpu").val();
var memory = jQuery("#memory").val();
var price = jQuery("#price").val();
var categories =[];
if(brand)
{
categories.push(brand);
}
if(screen_size)
{
categories.push(screen_size);
}
if(cpu)
{
categories.push(cpu);
}
if(memory)
{
categories.push(memory);
}
if(price)
{
categories.push(price);
}
length = categories.length;
categories2 = categories.toString();
alert(categories2);
var categories3="";
for(var i = 0; i < length; i++){
categories3 += "<div class='filter_style'>"+categories[i]+"<span style='margin-left:15px;color:gray;'>x</span></div>";
jQuery("#filter").html(categories3);
}
      });
});
</script>
 My HTML Code:
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="brand" >
<option value="">Select a Brand</option>
<option value="Lenovo">Lenovo</option>
<option value="Acer">Acer</option>
</select>
</div>
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="screen_size" style="margin-top:0px;">
<option value="">Select a Screen Size</option>
<option value="Small">Small</option>
<option value="Large">Large</option>
</select>
</div>
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="cpu">
<option value="">Select a CPU</option>
<option value="Intel">Intel</option>
<option value="Amd">Amd</option>
</select>
</div>
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="memory">
<option value="">Select a Memory</option>
<option value="500mb">500mb</option>
<option value="1tb">1tb</option>
</select>
</div>
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="price">
<option value="">Filter by Price</option>
<option value="10000">10000</option>
<option value="20000">20000</option>
</select>
</div>
</div>
There is possibilities, I will UPDATE the answer if it wasn't correct.
But first can you help what will you get after you run this code?
jQuery("#brand,#screen_size").change(function() {
var brand = jQuery("#brand").val();
var screen_size = jQuery("#screen_size").val();
console.log(brand);
console.log(screen_size);
});

Join inputs into one string

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>

Categories