I need to add a new select option in my HTML when they click it
<select class="statusButtonChange statusButton " data-value="49506">
<option value="0" selected=""></option>
<option value="1">Close</option>
<option value="2" disabled="" style="color:grey;">Taken</option>
</select>
This new option is dynamic and will be coming from an API response... I'm parsing the var value from the API response but for now, I made it static just to test.
Right now, I have this:
$(document).ready(function () {
var k = 1
$(".statusButton").on('focus', function () {
var value = "Disable";
var new_v = "";
var html = $(".statusButton").html();
if (k == 1) {
if (value == "Disable") {
new_v = "<option value='Disable' >Disable</option>";
}
else if (value == "Enable") {
new_v = "<option value='Enable' >Enable</option>"
}
var full = html + "" + new_v;
$(".statusButton").html(full);
k = 2;
}
});
});
It is working on JSFiddle but when I try to integrate it on my website, it's not reading it, even just the console log. WHat am I doing wrong?
I'm not sure exactly what's wrong, but I think a better approach might be to use jQuery's append method (https://api.jquery.com/append/).
Consider:
...
$(".statusButton").on('focus', function () {
var value = "Disable";
var new_v = "";
var $statusButton = $(".statusButton");
if(k == 1){
if(value == "Disable")
{
$statusButton.append("<option value='Disable' >Disable</option>");
}
else if(value == "Enable")
{
$statusButton.append("<option value='Enable' >Enable</option>")
}
...
If you do things that way, you don't have to mess around with any extra .html calls.
This is short answer without creating too many variable.
$(document).ready(function() {
var k = 1
$(".statusButton").on('focus', function() {
var value = "Disable";
if (k == 1) {
if (value == "Disable") {
$(".statusButton").append("<option value='Disable' >Disable</option>");
} else if (value == "Enable") {
$(".statusButton").append("<option value='Enable' >Enable</option>")
}
k = 2;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="statusButtonChange statusButton " data-value="49506">
<option value="0" selected=""></option>
<option value="1">Close</option>
<option value="2" disabled="" style="color:grey;">Taken</option>
</select>
Related
I want to stock multiples choices in a input hidden when I change my select (example I select the last option then the first option) I get in my input the same order .
$('select').change(function() {
var str = "";
// For multiple choice
$("select option:selected").each(function() {
str = $(this).val() + str + " ";
});
alert(str);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="brands[]" class="chosen selectbrands fixed-width-xl" id="brands[]" multiple="multiple">
<option value="1">BASTIEN test0</option>
<option value="2">BASTIEN test1</option>
<option value="3">BASTIEN test2</option>
</select>
Now If I change for example
(BASTIEN test1/BASTIEN test2/BASTIEN test0)
when I run my code I get
(BASTIEN test0/BASTIEN test1/BASTIEN test2)
this my code work fine but when I select the last then the second the problem here Is when I select the third one they don't work and I don't get the value of my option inside my var
If I understood you correctly this may help:
Target options directly with click event and save them in order in array.
With e.target.selected ? you make sure push is made on selected only.
remove function will remove element from array if deselected.
var str = []
$('select#brands option').on("click", function(e) {
let l = $(e.target).parent().find("option:selected").length
console.clear()
if (l > 1) {
e.target.selected ? str.push(e.target.value) : remove(str, e.target.value);
} else if (l === 1 && str.length != 2) {
str = [e.target.value]
} else if (l === 1 && str.length === 2) {
remove(str, e.target.value)
} else if (l === 0) {
str = []
}
console.log(str)
});
function remove(str, item) {
var index = str.indexOf(item);
if (index !== -1) {
str.splice(index, 1);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="brands[]" class="chosen selectbrands fixed-width-xl" id="brands" multiple="multiple">
<option value="1">BASTIEN test1</option>
<option value="2">BASTIEN test2</option>
<option value="3">BASTIEN test3</option>
<option value="4">BASTIEN test4</option>
</select>
Like this. When you select from the beginning, the options array is reset.
var str = "";
$('select').change(function() {
//alert($(this).find("option").length);
if($(this).find("option").length < str.split(" ").length){
str = "";
}
// For multiple choice
str = $(this).find("option:selected").val() + str + " ";
alert(str);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="brands[]" class="chosen selectbrands fixed-width-xl" id="brands[]" multiple="multiple">
<option value="1">BASTIEN test0</option>
<option value="2">BASTIEN test1</option>
<option value="3">BASTIEN test2</option>
</select>
First of all, sorry, I know the next code is wrong, I'm new in programming and I have a problem with it. When the user select an option from the Select, a value it must change, then, the user must write a price in numbers which value must not be higher than the previous value, here is when the scripts should act but it doesn't works. The correct code must be something like that:
<script>
function cboc(){
var cb = $("#cbotipfon").val();
var maxvalGORE = null;
if(cb == 0){
maxvalGORE = 0;
if(cb == 15){
maxvalGORE = 100;
}
if(cb == 16){
maxvalGORE = 200;
}
}
function cbocc(){
var val = null;
var x = document.GetElementById('txtprepos').value;
val = parseInt(x);
if(val > maxvalGORE){
alert('The value is higher than $' + maxvalGORE +'.');
document.GetElementById('txtprepos').value = "";
}
}
</script>
<select style="width=5.5em;" name="cbotipfon" id="cbotipfon" onchange="cboc()">
<option value="0">Select</option>
<option value="15">Option A</option>
<option value="16">Option B</option>
</select>
<input type="number" onblur="cbocc()" name="txtprepos" id="txtprepos"/>
I've been with that problem for days. If you can help me I'll be eternally grateful. Thanks in advance and for take your time.
Here is a simple example. No need to declare any function. Just declare your variables correctly and use the addEventListener method for getting the values of the input and select elements.
var maxvalGORE ,val ,cb ,x = null;
document.getElementById("cbotipfon").addEventListener("change", function(){
var cb = document.getElementById('cbotipfon').value;
if(cb == 0){
maxvalGORE = 0;
}
if(cb == 15){
maxvalGORE = 100;
}
if(cb == 16){
maxvalGORE = 200;
}
});
document.getElementById("txtprepos").addEventListener("change", function(){
x = document.getElementById('txtprepos').value;
val = parseInt(x);
if(val > maxvalGORE){
alert('The value is higher than $' + maxvalGORE +'.');
} else if(val == maxvalGORE) {
alert('The value is equal to $' + maxvalGORE +'.');
} else {
alert('The value is lower than $' + maxvalGORE +'.');
}
document.getElementById('txtprepos').value = "";
});
<select style="width=5.5em;" name="cbotipfon" id="cbotipfon">
<option value="0">Select</option>
<option value="15">Option A</option>
<option value="16">Option B</option>
</select>
<input type="number" name="txtprepos" id="txtprepos"/>
I'm trying to access the value of a selected option in a drop down menu. I continuously am left with an "undefined" value.
Here is the HTML list I created:
function setDifficulty() {
var difficultySelector = document.getElementById("difficulty");
var difficulty = difficultySelector.selectedIndex;
if (difficulty.options[difficulty.selectedIndex].value == "0") {
window.alert("easy");
} else if (difficulty.options[difficulty.selectedIndex].value == "1") {
window.alert("medium")
} else if (difficulty.options[difficulty.selectedIndex].value == "2") {
window.alert("hard");
} else
window.alert(difficulty.value);
}
<select id="difficulty" onchange="setDifficulty();">
<option value="0">Easy</option>
<option value="1">Medium</option>
<option value="2">Hard</option>
</select>
What am I doing wrong?
The following code will work
function setDifficulty() {
var difficultyElt = document.getElementById("difficulty");
var value = difficultyElt.options[difficultyElt.selectedIndex].value;
if (value == "0") {
window.alert("easy");
} else if (value == "1") {
window.alert("medium")
} else if (value == "2"){
window.alert("hard");
}
}
Also, you may output your text value directly:
var difficultyElt = document.getElementById("difficulty");
var text = difficultySelector.options[difficultySelector.selectedIndex].text;
window.alert(text);
You can easily get a value from input. You don't need these tricky calculations of value. Also, when you want to work with specific values it's better to use switch-case. It seems much cleaner and needs less code.
function setDifficulty() {
var difficultySelector = document.getElementById("difficulty");
var difficulty = difficultySelector.value;
switch (difficulty) {
case "0":
window.alert("easy");
break;
case "1":
window.alert("medium");
break;
case "2":
window.alert("hard");
break;
default:
window.alert(difficulty.value);
}
}
<select id="difficulty" onchange="setDifficulty();">
<option value="0">Easy</option>
<option value="1">Medium</option>
<option value="2">Hard</option>
</select>
I have two fields customer category and customer type,
when I select one element in customer category , I need to display only a set of elements from customer type in the drop down and rest should not appear.
how do write it in javascript. Here is the one I tried but it doesnot yield proper result.
var custcategory = document.getElementById("custcatid");
var custtypes = document.getElementById('custtypeid').options;
alert('yes');
var n = custtypes.length;
var allowedtype;
if (custcategory.options[custcategory.selectedIndex].value == "ANALOGUE") {
alert('ANALOGUE');
allowedtype = 'CATV,CATV RURAL';
}
else if (custcategory.options[custcategory.selectedIndex].value == "COMMERCIAL") {
alert('COMMERCIAL');
allowedtype = ' ,3ST HOTEL,4ST HOTEL,5ST HOTEL';
}
else if (custcategory.options[custcategory.selectedIndex].value == "DAS") {
alert('DAS');
allowedtype = ' ,DAS PHASE1,DAS PHASE2,DAS PHASE3,DAS PHASE4';
}
else if (custcategory.options[custcategory.selectedIndex].value == "DTH") {
alert('DTH');
allowedtype = ' ,DTH';
}
var idx = 0;
for (var i = 0; i < n; i++) {
var type = custtypes[i].value;
var found = allowedtype.search(type);
if (found <= 0) {
custtypes[i].style.display = 'none';
}
else if (idx == 0) {
idx = 1;
document.getElementById('ctl00_uxPgCPH_custtype').selectedIndex = i;
}
}
alert('Done..!');
If I understand correctly, you are trying to filter a second select element based on what is selected in the first select element?
If so I put together the following snippet which might help you out. It can be probably be optimised further but it should help to get you started I feel.
(function () {
var CLASSES = {
categories: '.select__category',
types : '.select__types'
},
map = {
ANALOGUE: [
'CATV',
'CATV RURAL'
],
COMMERCIAL: [
'3ST HOTEL',
'4ST HOTEL',
'5ST HOTEL'
],
DAS: [
'DAS PHASE 1',
'DAS PHASE 2',
'DAS PHASE 3'
]
},
categorySelect = document.querySelector(CLASSES.categories),
typeSelect = document.querySelector(CLASSES.types),
filterTypes = function(val) {
// Based on a value filter the types select.
var opts = typeSelect.options,
allowedOpts = map[val];
typeSelect.value = allowedOpts[0];
for(var i = 0; i < opts.length; i++) {
if (allowedOpts.indexOf(opts[i].value) === -1) {
opts[i].hidden = true;
} else {
opts[i].hidden = false;
}
}
};
filterTypes(categorySelect.value);
categorySelect.addEventListener('change', function(e) {
filterTypes(this.value);
});
}());
<!DOCTYPE html>
<head></head>
<body>
<select id="categories" class="select__category">
<option value="ANALOGUE">Analogue</option>
<option value="COMMERCIAL">Commercial</option>
<option value="DAS">Das</option>
</select>
<select id="types" class="select__types">
<option value="CATV">Catv</option>
<option value="CATV RURAL">Catv Rural</option>
<option value="3ST HOTEL">3st Hotel</option>
<option value="4ST HOTEL">4st Hotel</option>
<option value="5ST HOTEL">5st Hotel</option>
<option value="DAS PHASE 1">Das Phase 1</option>
<option value="DAS PHASE 2">Das Phase 2</option>
<option value="DAS PHASE 3">Das Phase 3</option>
</select>
</body>
If you run the snippet, you'll see that making changes to the first will update the second select accordingly based on the defined map.
Hope this can help you out!
I need to display the selected sub-categories (multi) in the below div and also in some situations I need to close the div elements that are selected wrongly from the select box, so that I can add and delete elements to the div (by the above selectbox).
Even I made the similar code, but its not working for multi selection.
Briefly, I need the selected categories (multi) with close buttons in the below div.
<script type="text/javascript">
function selectlist() {
checkboxhome = document.getElementById("check");
catogery = document.getElementById("cat");
value = catogery.options[catogery.selectedIndex].value;
checkboxhome.innerHTML = "<br/> <p>" + value + "</p>";
}
</script>
<body>
<form action="#" enctype="multipart/form-data">
<select name="cat" id="cat" onchange="selectlist();" multiple="multiple">
<option>Select subcatogery</option>
<option value="fashion">Fashion</option>
<option value="jewelry">Jewelry</option>
<option value="dresses">dresses</option>
<option value="shirts">Shirts</option>
<option value="diamonds">Diamonds</option>
</select>
<div id="check">
</div></form>
</body>
</html>
Loop over the options and check if they are selected, something like this:
function selectlist() {
var checkboxhome = document.getElementById("check");
var category = document.getElementById("cat");
checkboxhome.innerHTML = '';
for (var i = 0; i < category.options.length; i++) {
if (category[i].selected) {
checkboxhome.innerHTML += "<p>" + category.options[i].value + "</p>";
}
}
}
Here is a fiddle of what could work for you: http://jsfiddle.net/maniator/W6gnX/
Javascript:
function selectlist() {
checkboxhome = document.getElementById("check");
catogery = document.getElementById("cat");
value = getMultiple(catogery);
checkboxhome.innerHTML = "<br/> <p>" + value + "</p>";
}
function getMultiple(ob)
{
var arSelected = new Array(), length = ob.length, i = 0, indexes = [];
while (ob.selectedIndex != -1 && i < length)
{
if (ob.selectedIndex != 0 && !in_array(ob.selectedIndex, indexes)) {
indexes.push(ob.selectedIndex)
arSelected.push(ob.options[ob.selectedIndex].value);
}
ob.options[ob.selectedIndex].selected = false;
i++;
}
var count = 0;
while(count < indexes.length){
ob.options[indexes[count]].selected = true;
count ++;
}
return arSelected;
}
function in_array(needle, haystack)
{
for(var key in haystack)
{
if(needle === haystack[key])
{
return true;
}
}
return false;
}