Select option hide and show when counter changes - javascript

I have some dropdown menu where I want to hide value 550282, if amount of guests is greater to 2 and show when amount of guest is less or equal to 2.
Guest Count is added by JavaScript functions below.
Is this possible through jQuery or there is another method? Snipped code is there and also the [fiddle](https://jsfiddle.net/u3cbntb3/14/).
var hostAmount = 1;
var hosts = [1];
function getSelect(index) {
var retHTML = '<span class="label">Host ' + (index + 1) + ': </span><select name="host' + (index + 1) + '" id="host' + (index + 1) + '">';
if (hosts[index] == 1)
retHTML += '<option value="1" selected="selected">Dospělý</option><option value="2" >Dítě do 15</option><option value="3">Dítě do 10</option><option value="4">Přistýlka</option><option value="5">Vlastní postýlka</option></select>';
else
retHTML += '<option value="1">Dospělý (130Kč)</option><option value="2" selected="selected">Dítě do 15(130Kč)</option><option value="3">Dítě do 10(1Kč)</option><option value="4">Přistýlka</option><option value="5">Vlastní postýlka</option></select>';
if (index != 0)
retHTML += '<span class="delete" onclick="deleteHost(' + index + ');">Smazat</span><br />';
else
retHTML += '<br />';
return retHTML;
}
function saveValues() {
for (var i = 1; i < hostAmount; i++)
hosts[i] = document.getElementById("host" + (i + 1)).value;
}
function actualSelects() {
var HTMLbuff = "";
for (var i = 0; i < hosts.length; i++)
HTMLbuff += getSelect(i);
document.getElementById("personBox").innerHTML = HTMLbuff;
document.getElementById("amount").value = hostAmount;
}
function addHost() {
saveValues();
hosts.push(1);
hostAmount++;
actualSelects();
}
function deleteHost(index) {
hosts.splice(index, 1);
hostAmount--;
actualSelects();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body onload="actualSelects()">
<form>
<span class="label">Guest Count: </span><input readonly name="amount" id="amount" type="number" value="1" min="1" /><br />
<div id="personBox">
</div>
<span id="addPerson" onclick="addHost();">Add Host</span><br />
<span>Option</span>
<select name="room-type" class="dropdown-list">
<option id="toremove" selected="selected" value="550282">550282</option>
<option value="550280">550280</option>
<option value="557786">557786</option>
<option value="550284">557786</option>
</select>
</form>
</body>
</html>

Simply, you can hide the selection by document.getElementById("toremove").style.display="none";,
then show it up by document.getElementById("toremove").style.display=""; when guest count <=2.
var hostAmount = 1;
var hosts = [1];
function getSelect(index) {
var retHTML = '<span class="label">Host ' + (index + 1) + ': </span><select name="host' + (index + 1) + '" id="host' + (index + 1) + '">';
if (hosts[index] == 1)
retHTML += '<option value="1" selected="selected">Dospělý</option><option value="2" >Dítě do 15</option><option value="3">Dítě do 10</option><option value="4">Přistýlka</option><option value="5">Vlastní postýlka</option></select>';
else
retHTML += '<option value="1">Dospělý (130Kč)</option><option value="2" selected="selected">Dítě do 15(130Kč)</option><option value="3">Dítě do 10(1Kč)</option><option value="4">Přistýlka</option><option value="5">Vlastní postýlka</option></select>';
if (index != 0)
retHTML += '<span class="delete" onclick="deleteHost(' + index + ');">Smazat</span><br />';
else
retHTML += '<br />';
return retHTML;
}
function saveValues() {
for (var i = 1; i < hostAmount; i++)
hosts[i] = document.getElementById("host" + (i + 1)).value;
}
function actualSelects() {
var HTMLbuff = "";
for (var i = 0; i < hosts.length; i++)
HTMLbuff += getSelect(i);
document.getElementById("personBox").innerHTML = HTMLbuff;
document.getElementById("amount").value = hostAmount;
}
function addHost() {
saveValues();
hosts.push(1);
hostAmount++;
actualSelects();
if(hostAmount>2) {
document.getElementById("toremove").style.display="none";
document.getElementById("toselect").value = ""; //reset the value of select
}
else{
document.getElementById("toremove").style.display="";
}
}
function deleteHost(index) {
hosts.splice(index, 1);
hostAmount--;
actualSelects();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body onload="actualSelects()">
<form>
<span class="label">Guest Count: </span><input readonly name="amount" id="amount" type="number" value="1" min="1" /><br />
<div id="personBox">
</div>
<span id="addPerson" onclick="addHost();">Add Host</span><br />
<span>Option</span>
<select name="room-type" class="dropdown-list" id="toselect">
<option id="toremove" selected="selected" value="550282">550282</option>
<option value="550280">550280</option>
<option value="557786">557786</option>
<option value="550284">557786</option>
</select>
</form>
</body>
</html>

Related

I need to add a Feature / button that Increases the Cost with the number of Products?

Just trying to find a way to add an Increase cost with product button into an existing Var!.
function Total(qty, ud, total, value, cart) {
qty = document.getElementById("qty",);
ud > 0 ? qty.value++ : qty.value--;
qty.value = Math.max(qty.value, 0);
document.getElementById("total",).value = qty.value * value, Boys_Toys;
}
<div class="slider-vertical"></div>
<div id="purhcaseForm">
<form id="purchase">
<br> Item Price: $250
<br> Please Select Quantity
<input type='button' name='subtract' onclick='Total("qty",-1,"total",250);' value='-' />
<input type='button' name='add' onclick='Total("qty",1,"total",250);' value='+' />
<input type='text' name='qty' id='qty' readonly=true value="0" />
<input type='text' name='total' id='total' value="0" />
</form>
</div>
Is this what you looking for? Just a typo error!
function Total(qty, ud, total, value, cart) {
qty = document.getElementById("qty",);
ud > 0 ? qty.value++ : qty.value--;
qty.value = Math.max(qty.value, 0);
document.getElementById("total",).value = qty.value * value;
}
<div class="slider-vertical"></div>
<div id="purhcaseForm">
<form id="purchase">
<br> Item Price: $250
<br> Please Select Quantity
<input type='button' name='subtract' onclick='Total("qty",-1,"total",250);' value='-' />
<input type='button' name='add' onclick='Total("qty",1,"total",250);' value='+' />
<input type='text' name='qty' id='qty' readonly=true value="0" />
<input type='text' name='total' id='total' value="0" />
</form>
</div>
Is this what you meant?
const formDiv = document.getElementById("purhcaseFormDiv");
const totalSum = document.getElementById("total");
const slider = document.querySelector(".slider-vertical");
const arr = [{name:"Rubix cube", Cost:250, image:"Pictures/3x3-Rubix-Cube.jpg"},
{name:"Drone", Cost:5000, image:"Pictures/Rc.Drone.jpg"},
{name:"Aeroplane", Cost:3000, image:"Pictures/Rc.Plane.jpg"},
{name:"Cars", Cost:1500, image:"Pictures/Rc.Car.jpg"},
{name:"Rc.Hellio", Cost:1000, image:"Pictures/Rc.Hellio.jpg"},
{name:"Brown Teddy", Cost:800, image:"Pictures/Teddy.jpg"}];
const total = () => {
let totalAmt = 0;
let formHTML = []
let amt = 0;
arr.forEach((item, i) => {
if (item.qty && item.qty > 0) {
amt = item.qty * item.Cost;
formHTML.push(item.name + "<br/>Item Price: $" + item.Cost.toFixed(2) + "<br>Please Select Quantity" +
"<input type='button' class='subtract' value='-' data-idx='" + i + "'/>" +
"<input type='button' class='add' value='+' data-idx='" + i + "'/>" +
"<input type='text' name='qty' readonly=true value='" + item.qty + "' />" +
"<input type='text' name='subtotal' value='" + amt.toFixed(2) + "' />");
}
totalAmt += amt;
});
formDiv.innerHTML = formHTML.join("<hr/>");
totalSum.innerText = totalAmt.toFixed(2)
};
let html = [];
arr.forEach((item, i) => html.push(
'<div class="card"><h2>' + item.name + '</h2><img src=' + item.image + ' style="width:250px" border="3px"><p class="Cost">$ ' + item.Cost.toFixed(2) + '</p> <p> <button class="add" data-idx="' + i + '"> Add to cart </button> </p> </div>'))
slider.innerHTML = html.join("");
slider.addEventListener("click", (e) => {
const el = e.target;
if (el.className === "add") {
let i = el.getAttribute("data-idx");
if (arr[i].qty) {
arr[i].qty++
} else {
arr[i].qty = 1;
}
total()
}
})
formDiv.addEventListener("click", (e) => {
let el = e.target;
let cl = el.className;
let i = el.getAttribute("data-idx");
if (cl === "add" || cl === "subtract") {
let qty = arr[i].qty;
qty += cl === "add" ? 1 : -1;
arr[i].qty = qty < 0 ? 0 : qty;
total()
}
})
<div class="slider-vertical"></div>
<hr/>
<form id="purchaseForm">
<div id="purhcaseFormDiv"></div>
<hr/>
Total: $<span id="total">0.00</span>
</form>

how to display the selected text instead of values

Hi i have a piece of code & i couldn't display the selected text instead of values in fourth list box. Now, It displays the values of the option but i want to display the text i.e Paper Manufacturers << Paper Converters << Molded Pulp Products.
$(document).ready(function() {
var firstCategorySelector = '.select-manage-category';
var secondCategorySelector = '.select-manage-category1';
var thirdCategorySelector = '.select-manage-category2';
var firstCategory = $(firstCategorySelector);
var secondCategory = $(secondCategorySelector);
var thirdCategory = $(thirdCategorySelector);
var addCategoryButton = $("#add-category");
var removeCategoryButton = $('#remove-category');
var selectedList = $('#selected-lst-values');
var choice = $("#tget");
$('.select-manage-category, .select-manage-category1, .select-manage-category2').change(function() {
AddCategoryButtonEnable();
});
function getCategoryValues() {
var firstCategoryValue = firstCategory.val();
var secondCategoryValue = secondCategory.val();
var thirdCategoryValue = thirdCategory.val();
return [firstCategoryValue, secondCategoryValue, thirdCategoryValue];
}
function isDisableAddButton() {
var values = getCategoryValues();
return (!values[0] || !values[1] || !values[2]);
}
function AddCategoryButtonEnable() {
var isDisableAddCategoryButton = isDisableAddButton();
addCategoryButton.prop("disabled", isDisableAddCategoryButton).toggleClass('text-bold', isDisableAddCategoryButton);
}
function getNumberOfSelectedOption() {
return selectedList.find("option").length;
}
function getAvailableChoice() {
return 20 - parseInt(getNumberOfSelectedOption());
}
function setAvailableChoice($numChoice) {
var strText = ($numChoice !== 20) ? $numChoice + " more " : "up to 20 ";
choice.text(strText);
}
function appendChoice() {
var count="";
var givenCategoryArrayValue = getCategoryValues();
if ($('#selected-lst-values option:contains("' + givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] + '")').length > 0) {alert('This category has already been added.');
return count=1;
}
else {
selectedList.append('<option value="'+ givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] +'">' + givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] + '</option>');
return count=2;
}
}
addCategoryButton.click(function() {
var availableChoice = getAvailableChoice();
if (availableChoice >= 1) {
var a=appendChoice();
if(a==2){
setAvailableChoice(availableChoice - 1);
}
} else {
setAvailableChoice(0);
}
});
var option = selectedList.find('option:selected');
selectedList.change(function() {
removeCategoryButton.prop("disabled", false);
addCategoryButton.prop("disabled", true);
_addRemoveButtonClickListener();
});
function _addRemoveButtonClickListener() {
removeCategoryButton.click(function() {
selectedList.find('option:selected').remove();
var availableChoice = getAvailableChoice();
if (0 < availableChoice < 6) {
setAvailableChoice(availableChoice);
} else {
setAvailableChoice(0);
}
removeCategoryButton.prop("disabled", true);
});
}
});
.select-manage-category,
.select-manage-category1,
.select-manage-category2 {
width: 100px;
float: left;
margin-right: 4px;
}
p {
clear: left;
text-align: center;
}
#selected-lst-values {
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<select class="form-control select-manage-category" size="5">
<option value="1">Paper Manufacturers</option>
<option value="2">Paper Products Suppliers</option>
<option value="3">Paper Chemicals Suppliers</option>
</select>
</div>
<div>
<select class="form-control select-manage-category1" size="5">
<option value="1">Paper Converters</option>
<option value="2">Lab Apparatus & Supplies</option>
<option value="3">Service Providers</option>
</select>
</div>
<div>
<select class="form-control select-manage-category2" size="5">
<option value="1">Molded Pulp Products</option>
<option value="2">Software Vendors</option>
<option value="3">Information Services</option>
</select>
</div>
<p style="padding-top:10px;color:red;">You can add <span id="target">up to 5</span> categories</p>
</div>
<input id="add-category" name="add" type="button" value="Add Category" disabled="true">
<input id="remove-category" name="add" type="button" value="Remove Category" disabled="true">
<div>
<select id="selected-lst-values" class="form-group percent-100" size="7" multiple="multiple">
</select>
</div>
<button id="mnage-category-savebtn" class="btn btn-md btn-radius pi-btn prodetails-btn" type="button">
<strong>Save Categories</strong>
<span class="glyphicon glyphicon-menu-right right-arrow-head-icon"></span>
</button>
You should assign these texts which you want to get as the value of each options:
$(document).ready(function() {
var firstCategorySelector = '.select-manage-category';
var secondCategorySelector = '.select-manage-category1';
var thirdCategorySelector = '.select-manage-category2';
var firstCategory = $(firstCategorySelector);
var secondCategory = $(secondCategorySelector);
var thirdCategory = $(thirdCategorySelector);
var addCategoryButton = $("#add-category");
var removeCategoryButton = $('#remove-category');
var selectedList = $('#selected-lst-values');
var choice = $("#tget");
$('.select-manage-category, .select-manage-category1, .select-manage-category2').change(function() {
AddCategoryButtonEnable();
});
function getCategoryValues() {
var firstCategoryValue = firstCategory.val();
var secondCategoryValue = secondCategory.val();
var thirdCategoryValue = thirdCategory.val();
return [firstCategoryValue, secondCategoryValue, thirdCategoryValue];
}
function getCategoryDisplay() {
var firstCategoryDisplay = $(firstCategorySelector+" option:selected").text();
var secondCategoryDisplay = $(secondCategorySelector+" option:selected").text();
var thirdCategoryDisplay = $(thirdCategorySelector+" option:selected").text();
return [firstCategoryDisplay, secondCategoryDisplay, thirdCategoryDisplay];
}
function isDisableAddButton() {
var values = getCategoryValues();
return (!values[0] || !values[1] || !values[2]);
}
function AddCategoryButtonEnable() {
var isDisableAddCategoryButton = isDisableAddButton();
addCategoryButton.prop("disabled", isDisableAddCategoryButton).toggleClass('text-bold', isDisableAddCategoryButton);
}
function getNumberOfSelectedOption() {
return selectedList.find("option").length;
}
function getAvailableChoice() {
return 20 - parseInt(getNumberOfSelectedOption());
}
function setAvailableChoice($numChoice) {
var strText = ($numChoice !== 20) ? $numChoice + " more " : "up to 20 ";
choice.text(strText);
}
function appendChoice() {
var count="";
var givenCategoryArrayValue = getCategoryValues();
var givenCategoryArrayDisplay = getCategoryDisplay();
if ($('#selected-lst-values option:contains("' + givenCategoryArrayDisplay[0] + ' << ' + givenCategoryArrayDisplay[1] + ' << ' + givenCategoryArrayDisplay[2] + '")').length > 0) {alert('This category has already been added.');
return count=1;
}
else {
selectedList.append('<option value="'+ givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] +'">' + givenCategoryArrayDisplay[0] + ' << ' + givenCategoryArrayDisplay[1] + ' << ' + givenCategoryArrayDisplay[2] + '</option>');
return count=2;
}
}
addCategoryButton.click(function() {
var availableChoice = getAvailableChoice();
if (availableChoice >= 1) {
var a=appendChoice();
if(a==2){
setAvailableChoice(availableChoice - 1);
}
} else {
setAvailableChoice(0);
}
});
var option = selectedList.find('option:selected');
selectedList.change(function() {
removeCategoryButton.prop("disabled", false);
addCategoryButton.prop("disabled", true);
_addRemoveButtonClickListener();
});
function _addRemoveButtonClickListener() {
removeCategoryButton.click(function() {
selectedList.find('option:selected').remove();
var availableChoice = getAvailableChoice();
if (0 < availableChoice < 6) {
setAvailableChoice(availableChoice);
} else {
setAvailableChoice(0);
}
removeCategoryButton.prop("disabled", true);
});
}
});
.select-manage-category,
.select-manage-category1,
.select-manage-category2 {
width: 100px;
float: left;
margin-right: 4px;
}
p {
clear: left;
text-align: center;
}
#selected-lst-values {
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><select class="form-control select-manage-category" size="5">
<option value="1">Paper Manufacturers</option>
<option value="2">Paper Products Suppliers</option>
<option value="3">Paper Chemicals Suppliers</option>
</select></div>
<div><select class="form-control select-manage-category1" size="5">
<option value="1">Paper Converters</option>
<option value="2">Lab Apparatus & Supplies</option>
<option value="3">Service Providers</option>
</select></div>
<div><select class="form-control select-manage-category2" size="5">
<option value="1">Molded Pulp Products</option>
<option value="2">Software Vendors</option>
<option value="3">Information Services</option>
</select>
</div>
<p style="padding-top:10px;color:red;">You can add <span id="target">up to 5</span> categories</p>
</div>
<input id="add-category" name="add" type="button" value="Add Category" disabled="true">
<input id="remove-category" name="add" type="button" value="Remove Category" disabled="true">
<div><select id="selected-lst-values" class="form-group percent-100" size="7" multiple="multiple">
</select></div>
<button id="mnage-category-savebtn" class="btn btn-md btn-radius pi-btn prodetails-btn" type="button"><strong>Save Categories</strong> <span class="glyphicon glyphicon-menu-right right-arrow-head-icon"></span></button>
Updated: Defined new function getCategoryDisplay to get text of selected option as per your expected output in below comment.
It's a bit hard to tell how you want your final category data to be stored, but you can get the options to hold text descriptions instead of numbers by creating a getCategoryNames function and using it in place of getCategoryValues in appendChoice:
function getCategoryNames() {
return [].map.call(categories, function(e) {
return $(':selected', e).text()
})
}
It's also probably a good idea to give your selects a common class of .select-manage-category (without adding any numeric suffixes), because this simplifies your jQuery element selection:
var categories = $('.select-manage-category')
Demo Snippet:
$(document).ready(function() {
var categories = $('.select-manage-category')
var addCategoryButton = $("#add-category")
var removeCategoryButton = $('#remove-category')
var selectedList = $('#selected-lst-values')
var choice = $("#tget")
categories.change(AddCategoryButtonEnable)
function getCategoryValues() {
return [].map.call(categories, function(e) {
return e.value
})
}
function getCategoryNames() {
return [].map.call(categories, function(e) {
return $(':selected', e).text()
})
}
function isDisableAddButton() {
var values = getCategoryValues();
return (!values[0] || !values[1] || !values[2]);
}
function AddCategoryButtonEnable() {
var isDisableAddCategoryButton = isDisableAddButton();
addCategoryButton.prop("disabled", isDisableAddCategoryButton).toggleClass('text-bold', isDisableAddCategoryButton);
}
function getNumberOfSelectedOption() {
return selectedList.find("option").length;
}
function getAvailableChoice() {
return 20 - parseInt(getNumberOfSelectedOption());
}
function setAvailableChoice($numChoice) {
var strText = ($numChoice !== 20) ? $numChoice + " more " : "up to 20 ";
choice.text(strText);
}
function appendChoice() {
var count = "";
var givenCategoryArrayValue = getCategoryValues().join(' << ');
if ($('#selected-lst-values option[value="' + givenCategoryArrayValue + '"]').length > 0) {
alert('This category has already been added.');
return count = 1;
} else {
selectedList.append(new Option(getCategoryNames().join(' << '), givenCategoryArrayValue));
return count = 2;
}
}
addCategoryButton.click(function() {
var availableChoice = getAvailableChoice();
if (availableChoice >= 1) {
var a = appendChoice();
if (a == 2) {
setAvailableChoice(availableChoice - 1);
}
} else {
setAvailableChoice(0);
}
});
var option = selectedList.find(':selected');
selectedList.change(function() {
removeCategoryButton.prop("disabled", false);
addCategoryButton.prop("disabled", true);
_addRemoveButtonClickListener();
});
function _addRemoveButtonClickListener() {
removeCategoryButton.click(function() {
selectedList.find('option:selected').remove();
var availableChoice = getAvailableChoice();
if (0 < availableChoice < 6) {
setAvailableChoice(availableChoice);
} else {
setAvailableChoice(0);
}
removeCategoryButton.prop("disabled", true);
});
}
});
.select-manage-category {
width: 100px;
float: left;
margin-right: 4px;
}
p {
clear: left;
text-align: center;
}
#selected-lst-values {
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><select class="form-control select-manage-category" size="5">
<option value="1">Paper Manufacturers</option>
<option value="2">Paper Products Suppliers</option>
<option value="3">Paper Chemicals Suppliers</option>
</select></div>
<div><select class="form-control select-manage-category" size="5">
<option value="1">Paper Converters</option>
<option value="2">Lab Apparatus & Supplies</option>
<option value="3">Service Providers</option>
</select></div>
<div><select class="form-control select-manage-category" size="5">
<option value="1">Molded Pulp Products</option>
<option value="2">Software Vendors</option>
<option value="3">Information Services</option>
</select>
</div>
<p style="padding-top:10px;color:red;">You can add <span id="target">up to 5</span> categories</p>
<input id="add-category" name="add" type="button" value="Add Category" disabled="true">
<input id="remove-category" name="add" type="button" value="Remove Category" disabled="true">
<div><select id="selected-lst-values" class="form-group percent-100" size="7" multiple="multiple">
</select></div>
<button id="mnage-category-savebtn" class="btn btn-md btn-radius pi-btn prodetails-btn" type="button"><strong>Save Categories</strong> <span class="glyphicon glyphicon-menu-right right-arrow-head-icon"></span></button>
var firstCategoryValue = firstCategory.val(); will return the array of selected values.
To get the array of selected text use
$('.select-manage-category :selected').each(function(i, v) {
firstCategoryValue[i] = $(v).text();
});
Updated Snippet:
$(document).ready(function() {
var firstCategorySelector = '.select-manage-category';
var secondCategorySelector = '.select-manage-category1';
var thirdCategorySelector = '.select-manage-category2';
var firstCategory = $(firstCategorySelector);
var secondCategory = $(secondCategorySelector);
var thirdCategory = $(thirdCategorySelector);
var addCategoryButton = $("#add-category");
var removeCategoryButton = $('#remove-category');
var selectedList = $('#selected-lst-values');
var choice = $("#tget");
$('.select-manage-category, .select-manage-category1, .select-manage-category2').change(function() {
AddCategoryButtonEnable();
});
function getCategoryValues() {
var firstCategoryValue = [];
var secondCategoryValue = [];
var thirdCategoryValue = [];
$('.select-manage-category :selected').each(function(i, v) {
firstCategoryValue[i] = $(v).text();
});
$('.select-manage-category1 :selected').each(function(i, v) {
secondCategoryValue[i] = $(v).text();
});
$('.select-manage-category2 :selected').each(function(i, v) {
thirdCategoryValue[i] = $(v).text();
});
return [firstCategoryValue, secondCategoryValue, thirdCategoryValue];
}
function isDisableAddButton() {
var values = getCategoryValues();
return (!values[0] || !values[1] || !values[2]);
}
function AddCategoryButtonEnable() {
var isDisableAddCategoryButton = isDisableAddButton();
addCategoryButton.prop("disabled", isDisableAddCategoryButton).toggleClass('text-bold', isDisableAddCategoryButton);
}
function getNumberOfSelectedOption() {
return selectedList.find("option").length;
}
function getAvailableChoice() {
return 20 - parseInt(getNumberOfSelectedOption());
}
function setAvailableChoice($numChoice) {
var strText = ($numChoice !== 20) ? $numChoice + " more " : "up to 20 ";
choice.text(strText);
}
function appendChoice() {
var count = "";
var givenCategoryArrayValue = getCategoryValues();
if ($('#selected-lst-values option:contains("' + givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] + '")').length > 0) {
alert('This category has already been added.');
return count = 1;
} else {
selectedList.append('<option value="' + givenCategoryArrayValue[0].value + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] + '">' + givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] + '</option>');
return count = 2;
}
}
addCategoryButton.click(function() {
var availableChoice = getAvailableChoice();
if (availableChoice >= 1) {
var a = appendChoice();
if (a == 2) {
setAvailableChoice(availableChoice - 1);
}
} else {
setAvailableChoice(0);
}
});
var option = selectedList.find('option:selected');
selectedList.change(function() {
removeCategoryButton.prop("disabled", false);
addCategoryButton.prop("disabled", true);
_addRemoveButtonClickListener();
});
function _addRemoveButtonClickListener() {
removeCategoryButton.click(function() {
selectedList.find('option:selected').remove();
var availableChoice = getAvailableChoice();
if (0 < availableChoice < 6) {
setAvailableChoice(availableChoice);
} else {
setAvailableChoice(0);
}
removeCategoryButton.prop("disabled", true);
});
}
});
.select-manage-category,
.select-manage-category1,
.select-manage-category2 {
width: 100px;
float: left;
margin-right: 4px;
}
p {
clear: left;
text-align: center;
}
#selected-lst-values {
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><select class="form-control select-manage-category" size="5">
<option value="1">Paper Manufacturers</option>
<option value="2">Paper Products Suppliers</option>
<option value="3">Paper Chemicals Suppliers</option>
</select></div>
<div><select class="form-control select-manage-category1" size="5">
<option value="1">Paper Converters</option>
<option value="2">Lab Apparatus & Supplies</option>
<option value="3">Service Providers</option>
</select></div>
<div><select class="form-control select-manage-category2" size="5">
<option value="1">Molded Pulp Products</option>
<option value="2">Software Vendors</option>
<option value="3">Information Services</option>
</select>
</div>
<p style="padding-top:10px;color:red;">You can add <span id="target">up to 5</span> categories</p>
</div>
<input id="add-category" name="add" type="button" value="Add Category" disabled="true">
<input id="remove-category" name="add" type="button" value="Remove Category" disabled="true">
<div><select id="selected-lst-values" class="form-group percent-100" size="7" multiple="multiple">
</select></div>
<button id="mnage-category-savebtn" class="btn btn-md btn-radius pi-btn prodetails-btn" type="button"><strong>Save Categories</strong> <span class="glyphicon glyphicon-menu-right right-arrow-head-icon"></span></button>

how to validate dynamically created textbox which have the time value

I was stuck to this problem which I was thinking easy,problem is to validate dynamically created textbox value,from first textbox I have write from value 01:00 and to value as 03:00,in the second textbox I have write value as '02:00' to '04:00' so I want to validate this when i will click on the validate button it should restricted it because this value ("02:00"-"04:00") is coming in between ("01:00-03:00"), so it should validated and to validate at other newly created dynamic textboxes
------------------------------------------------------------
|from 01:00 to 03:00
|from 02:00 to 04:00 **restriction**
|from 03:00 to 05:00 right value(validated)
......
....
--------------------------------------------------------------
Here is my code for creating dynamic checkboxes and checks
jQuery add / remove textbox example
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.js"></script>
<style type="text/css">
div{
padding:8px;
}
</style>
</head>
<body>
<h1>jQuery add / remove textbox example</h1>
<script type="text/javascript">
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
if(counter>10){
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>From'+ counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >'+'<label>To'+ counter + ' : </label>' +
'<input type="text" name="totime' + counter +
'" id="totime' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if(counter==1){
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
$("#getButtonValue").click(function () {
var msg = '';
var $textbox='';
for(i=1; i<counter; i++){
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
$("#validate").click(function () {
msg=$('#textbox' + 1).val();
$textbox1= $('#textbox1').val();
$totime= $('#totime1').val();
$textbox2= $('#textbox2').val();
if($textbox2>=$textbox1&&$textbox2<=$totime)
{
alert("true");
}
else
{
alert("false");
}
});
});
</script>
</head>
<body>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>From : </label><input type='textbox' id='textbox1' > <label>To : </label><input type='textbox' id='totime1' >
</div>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<input type='button' value='Get TextBox Value' id='getButtonValue'>
<input type='button' value='Validate' id='validate'>
</body>
</html>
You should try this code
<html>
<head>
<title>jQuery add / remove textbox example</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.js"></script>
<style type="text/css">
div{
padding:8px;
}
</style>
</head>
<body>
<h1>jQuery add / remove textbox example</h1>
<script type="text/javascript">
$(document).ready(function () {
var counter = 2;
$("#addButton").click(function () {
if (counter > 10) {
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv' + counter).attr("class", 'time');
newTextBoxDiv.after().html('<label>From' + counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >' + '<label>To' + counter + ' : </label>' +
'<input type="text" name="totime' + counter +
'" id="totime' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if (counter == 1) {
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
$("#getButtonValue").click(function () {
var msg = '';
var $textbox = '';
for (i = 1; i < counter; i++) {
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
$("#validate").click(function () {
$i = 1;
$('.time').each(function () {
//alert('i='+$i);
$txtval = $('#TextBoxDiv' + $i).find('#textbox' + $i).val();
val= ($i + 1);
for ($j = val; $j >= 0; $j--)
{
// alert('asdads='+$j);
if ($txtval > $('#TextBoxDiv' + ($i - $j)).find('#textbox' + ($i - $j)).val() && $txtval < $('#TextBoxDiv' + ($i - 1)).find('#totime' + ($i - 1)).val())
{
$('#TextBoxDiv' + $i).find('#textbox' + $i).val("");
alert('restriction');
}
}
$i++;
});
});
});
</script>
</head>
<body>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1" class="time">
<label>From : </label><input type='textbox' id='textbox1' > <label>To : </label><input type='textbox' id='totime1' >
</div>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<input type='button' value='Get TextBox Value' id='getButtonValue'>
<input type='button' value='Validate' id='validate'>
</body>
</html>

Jquery add and remove DIV tag row based on select value

I found this great stackoverflow post that does what I need: add and remove rows based on a select value, but the only difference is that in my case, I don't have a table but blocks of divs. In the table example it works fine, but with divs it fails.
I've been using the console to try to fix it to no avail. It seems there are problems with the index value and the increment, but I don't undertand why with a table row works but with divs it doesnot. Could anyone take a look?
Here's a jsfiddle that shows the issue: http://jsfiddle.net/njes3w1a/1/
This is my script:
if ($('#returnRequest').length) {
var row_i = 0;
function emptyRow() {
row_i++;
this.obj = $('<div class="return-row control-group row"></div>');
this.obj.append('<div class="col-md-6"><label class="control-label">Serial number</label><input type="text" class="form-control" value=""/></div><div class="col-md-4"><label class="control-label">Item is</label><select class="form-control"><option value="">Select</option><option value="1">New and unopened</option><option value="2">Defective</option></select></div>');
}
function refresh(new_count) {
//how many applications we have drawed now ?
console.log("New count= " + new_count);
if (new_count > 0) {
$("#noa_header").show();
} else {
$("#noa_header").hide();
}
var old_count = parseInt($('#productRowWrapper').children().length);
console.log("Old count= " + old_count);
//the difference, we need to add or remove ?
var rows_difference = parseInt(new_count) - old_count;
console.log("Rows diff= " + rows_difference);
//if we have rows to add
if (rows_difference > 0) {
console.log('enetered a');
for (var i = 0; i < rows_difference; i++)
$('#productRowWrapper').append((new emptyRow()).obj);
} else if (rows_difference < 0) //we need to remove rows ..
{
console.log('enetered b');
var index_start = old_count + rows_difference + 1;
console.log("Index start= " + index_start);
$('.return-row:gt(' + index_start + ')').remove();
console.log(row_i);
console.log(rows_difference);
row_i += rows_difference;
console.log(row_i);
}
}
$('#quantityReturn').change(function () {
refresh($(this).val());
});
}
I would use this code:
if ($('#returnRequest').length) {
function emptyRow() {
this.obj = $('<div class="return-row control-group row"></div>');
this.obj.append(
'<input type="text" class="form-control" value=""/>' +
'<select class="form-control">' +
'<option value="">Select</option>' +
'<option value="1">New and unopened</option>' +
'<option value="2">Defective</option>' +
'</select>');
}
function refresh(count) {
if (count > 0) {
$("#noa_header").show();
} else {
$("#noa_header").hide();
}
var wrapper = $('#productRowWrapper');
while (wrapper.children().length > count)
wrapper.children().last().remove();
while (wrapper.children().length < count)
wrapper.append((new emptyRow()).obj);
}
$('#quantityReturn').change(function () {
refresh(parseInt($(this).val()));
});
}
It does not introduce unnecessary variables and it a bit shorter. Updated fiddle at http://jsfiddle.net/njes3w1a/6/.
you were calculating your strt index wrong add this
var index_start =old_count- Math.abs(rows_difference)-1 ;
Code
if ($('#returnRequest').length) {
var row_i = 0;
function emptyRow() {
row_i++;
this.obj = $('<div class="return-row control-group row"></div>');
this.obj.append('<input type="text" class="form-control" value=""/><select class="form-control"><option value="">Select</option><option value="1">New and unopened</option><option value="2">Defective</option></select>');
}
function refresh(new_count) {
//how many applications we have drawed now ?
console.log("New count= " + new_count);
if (new_count > 0) {
$("#noa_header").show();
} else {
$("#noa_header").hide();
}
var old_count = parseInt($('#productRowWrapper').children().length);
console.log("Old count= " + old_count);
//the difference, we need to add or remove ?
var rows_difference = parseInt(new_count) - old_count;
console.log("Rows diff= " + rows_difference);
//if we have rows to add
if (rows_difference > 0) {
console.log('enetered a');
for (var i = 0; i < rows_difference; i++)
$('#productRowWrapper').append((new emptyRow()).obj);
} else if (rows_difference < 0) //we need to remove rows ..
{
console.log('enetered b');
var index_start =old_count- Math.abs(rows_difference)-1 ;
console.log("Index start= " + index_start);
console.log('.return-row:gt(' + index_start + ')');
$('.return-row:gt(' + index_start + ')').remove();
console.log(row_i);
console.log(rows_difference);
row_i += rows_difference;
console.log(row_i);
}
}
$('#quantityReturn').change(function () {
refresh($(this).val());
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="" id="returnRequest">
<div class="form-group row">
<p class="col-sm-3 control-label">* Quantity to return</p>
<div class="col-sm-9">
<div class="row control-group">
<div class="col-sm-6 control-item" id="signupForename">
<select class="form-control" id="quantityReturn">
<option value="0">Please select</option>
<option value="1">1 item</option>
<option value="2">2 items</option>
<option value="3">3 items</option>
<option value="4">4 items</option>
</select>
</div>
</div>
</div>
</div>
<div class="panel panel-info">
<div class="pane-body">
<div class="form-group row">
<div class="col-sm-9">
<div id="noa_header" style="display: none;">Header</div>
<div id="productRowWrapper"></div>
</div>
</div>
</div>
</div>
</div>

Retrieving input from dynamically created forms in javascript

I am new to javascript and html and I am writing a program that displays a dropdown list and depending on what option is selected, I then display two radio buttons and a textfield. I am having trouble getting access to the values of these inputs (both for the radio buttons and for the text box).
<html>
<script type="text/javascript">
window.onload = function()
{
var select = document.getElementById("select");
var texts = document.getElementById("texts");
select.onchange = function()
{
var val = select.options[select.selectedIndex].value;
texts.innerHTML = "";
if (val == "employees")
{
texts.innerHTML += '<div><input type="radio" name="condition_employees" value="select_money" /> ></div>';
texts.innerHTML += '<div><input type="radio" name="condition_employees" value="select_money1" /> <</div>';
texts.innerHTML += '<div><input type="text" name="input_employees" value="select_employees" /></div>';
//var realValue = document.getElementByName('input_employees')[0].value;
//texts.innerHTML += '<div>realValue</div>';
}
if (val == "total_money")
{
texts.innerHTML += '<div><input type="radio" name="condition_money" value="select_money" /> ></div>';
texts.innerHTML += '<div><input type="radio" name="condition_money" value="select_money1" /> <</div>';
texts.innerHTML += '<div><input type="text" name="input_money"' + '" value="select_money" /></div>';
}
if (val == "hits")
{
texts.innerHTML += '<div><input type="radio" name="condition_hits" value="select_money" /> ></div>';
texts.innerHTML += '<div><input type="radio" name="condition_hits" value="select_money1" /> <</div>';
texts.innerHTML += '<div><input type="text" name="input_hits"' + '" value="select_hits" /></div>';
}
if (val == "time_founded")
{
texts.innerHTML += '<div><input type="radio" name="condition_time" value="select_money" /> before date </div>';
texts.innerHTML += '<div><input type="radio" name="condition_time" value="select_money1" /> after date</div>';
texts.innerHTML += '<div><input type="text" name="input_time"' + '" value="select_date" /></div>';
}
}
}
var print = function()
{
var category = document.droplist.select.value;
document.getElementById("category").innerHTML = category
}
</script>
<body>
<form name="droplist" action="html_form_action.asp" method = "get">
<select id="select" size="1">
<option value=" " selected="selected"> </option>
<option value="employees">Number of Employees</option>
<option value="hits">Hits on TechCrunch</option>
<option value="time_founded">Time Founded</option>
<option value="total_money">Total Money</option>
</select>
<hr/>
<div id="texts"></div>
<input type="button" value="Submit" onClick="print()"/>
</form>
<div id="category"></div>
</body>
I tried to do this by using "//var realValue = document.getElementByName('input_employees')[0].value;" but this is clearly not working. I would also like to know how to then pass on this information as a paramater for a function in my python app.
Thanks!
Might I suggest the following:
Don't re-write the <div>s in your javascript. You can write to the <div>'s innerHTML.
Instead of constantly writing these values, why not disable/enable as necessary?
I unfortunately cannot comment on the question, so I had to post here. Sorry about that.

Categories