Alerting JS Array Selection - javascript

I have a select with options that I am putting into an array, and I am attempting to alert a specific message when you click a button, but only if the proper array[x] has been selected. However, when I click the button, regardless of the option I get the message. What am I doing wrong?
Code:
HTML:
<button id="button">Click Me</button>
<br />
<br />
<select id = "list" value = "list">
<option id="one" value="one">
one
</option>
<option id="two" value="two">
two
</option>
<option id="three" value="three">
three
</option>
</select>
JS:
var listArr = [];
var button = document.getElementById("button");
var list = document.getElementById("list");
var selected = document.getElementById("list").selectedIndex;
for (var i = 0; i < list.options.length; i++) {
listArr[i] = list.options[i].value;
}
button.onclick = function() {
if (selected = [1]) {
alert("hello");
}
};

You cannot compare arrays like this. You need to use literal number instead. JSFiddle
var listArr = [];
var button = document.getElementById("button");
var list = document.getElementById("list");
var selected = document.getElementById("list");
for(var i = 0; i < list.options.length; i++) {
listArr[i] = list.options[i].value;
}
button.onclick = function() {
if(selected.selectedIndex == 1) {
alert('hello');
}
};

If I have understood your question correctly, you need the updated value of the select:
button.onclick = function()
{
if(document.getElementById("list").selectedIndex==1) // Also change = to ==
{
alert("hello");
}
};
https://jsfiddle.net/6bs1vjva/1/

Related

How to remove duplicate values coming from option tag

I have an Select tag with multiple options.On button click every selected option creates an li with innerText set to text value of the option. How would i make a function that i cant add the same element twice?
$(".btn").on("click", function () {
let selectedItems = $("#node-input-options option:selected");
selectedItems.each(function (i, el) {
// console.log(el, i);
let text = $(el).text();
let val = $(el).val();
var li = $("<li>").text(text).val(val).attr("title", val);
list.append(li);
li.on("dblclick", function () {
li.remove();
});
});
This is my code in jquery.
This is and example on fiddle => https://jsfiddle.net/nah062ck/11/
> You can use Jquery contains selector to check if a selected item already exists in the list.
$("#b1").on("click", function() {
var selectedItems = $("#cars option:selected");
let list = $(".list");
selectedItems.each(function(i,el) {
var text = $(el).text();
var val = $(el).val();
var li = $("<li>").text(text).val(val).attr('title', val).attr("size",10);
li.size = 10;
var exists=$('.list li:contains('+text+')');
if(exists.length > 0){
alert('The Selected Word already exists');
return
}
list.append(li);
});
});
$("#b1").on("click", function() {
var selectedItems = $("#cars option:selected");
let list = $(".list");
selectedItems.each(function(i, el) {
var text = $(el).text();
var val = $(el).val();
var li = $("<li>").text(text).val(val).attr('title', val).attr("size", 10);
li.size = 10
let c = 0
if ($(".list li").length === 0) {
list.append(li)
// if list is empty fill it
} else {
$(".list li").each(function(i, el2) {
$(el2).text() == text ? c = "x" : null
// if not empty, check if text exists in list under each li
})
}
c === 0 ? list.append(li) : console.log(false)
// do according
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select size="7" name="cars" id="cars" multiple>
<option value="cup">Cupcake</option>
<option value="cupas">Cunut</option>
<option value="cup124">Eclair</option>
<option value="cup2512">Froyo</option>
<option>Gingerbread</option>
</select>
<button id="b1">Click me</button>
<ul class="list"></ul>
After you append to list you can disable and unselect using .prop({'disabled': true, selected:false})
Then in your remove process look for that same option and enable it again.
$("#b1").on("click", function() {
var selectedItems = $("#cars option:selected");
let list = $(".list");
selectedItems.each(function(i, el) {
var text = $(el).text();
var val = $(el).val();
var li = $("<li>").text(text).attr('title', val);
list.append(li);
}).prop({disabled: true, selected: false});
});
$('.list').on('dblclick', 'li', function() {
const $li = $(this),
title = $li.attr('title');
$("#cars option[value='" + title + "']").prop('disabled', false)
$li.remove()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select size="7" name="cars" id="cars" multiple>
<option value="cup">Cupcake</option>
<option value="cupas">Cunut</option>
<option value="cup124">Eclair</option>
<option value="cup2512">Froyo</option>
<option>Gingerbread</option>
</select>
<button id="b1">Click me</button>
<ul class="list"></ul>
let addEl = document.getElementById("add-country");
let containerList = document.getElementById("country-list");
let countries = [];
addEl.onclick = function(e) {
e.preventDefault();
let selectEl = document.getElementById("country").value;
if (!(countries.includes(selectEl))) {
countries.push(selectEl);
let createElLi = document.createElement("LI");
createElLi.innerHTML = selectEl;
containerList.appendChild(createElLi);
}
}
<form method="get" accept-charset="utf-8">
<select name="country" id="country">
<option>Japan</option>
<option>USA</option>
<option>India</option>
<option>Bangladesh</option>
<option>Canada</option>
<option>Pakistan</option>
</select>
<input type="submit" value="Add" id="add-country">
</form>
<ul id="country-list"></ul>
Code :
<html>
<head>
<title>Remove Duplicate Options</title>
</head>
<body>
<select id='mylist'>
<option value='php'>PHP</option>
<option value='css'>CSS</option>
<option value='php'>PHP</option>
<option value='sql'>SQL</option>
<option value='js'>JS</option>
<option value='css'>CSS</option>
<option value='js'>JS</option>
</select>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js'></script>
<script>
function removeduplicate()
{
var mycode = {};
$("select[id='mylist'] > option").each(function () {
if(mycode[this.text]) {
$(this).remove();
} else {
mycode[this.text] = this.value;
}
});
}
</script>
<button onClick='removeduplicate()'>Remove Duplicate</button>
</body>
</html
Reference : Narendra Dwivedi - Remove Duplicate DropDown Option

How to Get the Result Using Javascript

I am working with this code and would like to get the result inside intTotal. But it doesn't give me the result I wish.
window.onload = function() {
var intNum = document.getElementById("intNum");
for (var i = 1; i <= 3000; i++) {
var option = document.createElement("option");
option.innerHTML = i;
option.value = i;
intNum.appendChild(option);
}
};
function jml_total() {
var hrg_sat = parseInt(document.querySelector("hrg_sat").innerHTML);
var jml_pilih = parseInt(document.getElementById("intNum").value);
var int_hitung = hrg_sat * jml_pilih;
document.getElementById("intTotal").value = int_hitung;
}
<div id="hrg_sat">3000</div>
<select id="intNum" onChange="jml_total(this.value)">
<option value="" disabled selected>Pilih Jumlah ... </option>
</select>
<br />
<div id="intTotal"></div>
I tried this thread. Or, you have the simplest one, but not using jquery.
You need to specify that hrg_sat is an id on your querySelector by using # as prefix
var hrg_sat = parseInt(document.querySelector("#hrg_sat").innerHTML);
Also, as the previous answer has mentioned, you need to use innerHTML property instead of value to display the text on the DOM on a <div> element
window.onload = function() {
var intNum = document.getElementById("intNum");
for (var i = 1; i <= 3000; i++) {
var option = document.createElement("option");
option.innerHTML = i;
option.value = i;
intNum.appendChild(option);
}
};
function jml_total() {
var hrg_sat = parseInt(document.querySelector("#hrg_sat").innerHTML);
var jml_pilih = parseInt(document.getElementById("intNum").value);
var int_hitung = hrg_sat * jml_pilih;
document.getElementById("intTotal").innerHTML = int_hitung;
}
<div id="hrg_sat">3000</div>
<select id="intNum" onChange="jml_total(this.value)">
<option value="" disabled selected>Pilih Jumlah ... </option>
</select>
<br />
<div id="intTotal"></div>
Since intTotal is a div, you want to use innerHTML not value. value in the post you linked to is for an input control, not a div
document.getElementById("intTotal").innerHTML = 'your content goes here';
<div id="intTotal"></div>

How to get the value from N dynamic inputs

I have a select with an options, this options have the number of inputs that user want to draw, after that user can type information in that inputs and finally they have to click a button to display that values, right now I'm doing this like this:
var value1 = $('#Input1').val();
The problem here is that the user can create a maximum of 200 inputs, so if I keep doing this in the above way I'll need to do that with the 200 inputs and it's a lot of code lines, my question is if exits a way to get the value of N inputs, I draw the inputs dynamically with a for loop, so all the input ID is something like Input(MyForVariable), Input1, Input2... etc, so maybe I'm thinking in create another loop to get the value of that inputs, here is my code:
$(document).ready(function () {
$('#sel').change(function () {
draw();
});
$('#btn').click(function () {
show();
});
});
function draw() {
var selected = $('#sel').val();
var html = "";
for (i = 1; i <= selected; i++) {
html += '<input type="text" id="Imput' + i + '" />';
}
$('#forms').html(html);
}
function show() {
var total = $('#sel').val();
if (total == 2) {
var val1 = $('#Imput1').val();
var val2 = $('#Imput2').val();
alert(val1 + val2);
}
if (total == 3) {
var val1 = $('#Imput1').val();
var val2 = $('#Imput2').val();
var val3 = $('#Imput3').val();
alert(val1 + val2 + val3);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="sel">
<option value="2">A</option>
<option value="3">B</option>
<option value="4">C</option>
<option value="5">D</option>
</select>
<div id="forms">
</div>
<button id="btn">Click</button>
Put all your inputs inside a container, and loop through them:
$('#add').on('click', function () {
$('<input />').appendTo('#myinputs');
});
$('#get').on('click', function () {
var values = [];
$('#myinputs input').each(function () {
values.push(this.value);
});
console.log(values);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="myinputs">
<input />
</div>
<button id="add">Add another input</button>
<hr />
<button id="get">Get values</button>
You can set some attribute and get all elements that has it:
$(document).ready(function () {
$('#sel').change(function () {
draw();
});
$('#btn').click(function () {
show();
});
});
function draw() {
var selected = $('#sel').val();
var html = "";
for (i = 1; i <= selected; i++) {
html += '<input type="text" id="Imput' + i + '" to-count />';
}
$('#forms').html(html);
}
function show() {
var total = $('#sel').val();
var sum = "";
var inputs = $('[to-count]');
console.log(inputs.length);
for (let i=0; i < inputs.length ; i++){
sum += inputs[i].value;
}
alert(sum);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="sel">
<option value="2">A</option>
<option value="3">B</option>
<option value="4">C</option>
<option value="5">D</option>
</select>
<div id="forms">
</div>
<button id="btn">Click</button>
You can get the values for each of the Select options by using the following code:
$("#sel option").each(function() {
console.log($(this).val());
});
You can always loop throw your inputs like this:
var myInputArray = [];
$('input[type="text"]').each(function(){
myInputArray.push($(this).val());
}
Then you can get your values by locking in the array:
alert(myInputArray[0]) //The first value of the array => first input

get the multiple selection as comma separated from select box into a text input

I don't know js. I need to get the multiple selection as comma separated from select box into a text input.
with pure js, I found only this question related on SO. Multiple selections into input box
And I tried the js code in that question. (question js combination with accepted answer)
However I couldn't achieve.
what I need is for example printing Australia,England into text input after selecting those 2 and submitting.
Fiddle link is:
http://jsfiddle.net/0k2m7gLo/
CODE IN FIDDLE
HTML
<form>
<select id="countries" multiple>
<option value="val0">Australia</option>
<option value="val1">England</option>
<option value="val2">France</option>
</select>
<input type="button" value="Show Index" onclick="showSelected();" />
</form>
<p>selected countries by comma seperated</p>
<form><input type="text" id="txtText" /></form>
UNSUCCESSFUL JS
function showSelected()
{
var selObj = document.getElementById('countries');
var txtTextObj = document.getElementById('txtText');
var selIndex = selObj.selectedIndex;
txtTextObj.value += selObj.options[selIndex].text +', ';
}
You can do something like this:
var selObj = document.getElementById('countries'),
txtTextObj = document.getElementById('txtText'),
selected = [];
for(var i = 0, l = selObj.options.length; i < l; i++){
//Check if the option is selected
if(selObj.options[i].selected){
selected.push(selObj.options[i].textContent);
}
}
txtTextObj.value = selected.join(', ');
jsFiddle
function updateSelected() {
var select = document.getElementById('countries'),
options = select.options,
input = document.getElementById('selected');
var selected = [];
for (var i = 0, ii = options.length; i < ii; ++i) {
var opt = options[i];
if (opt.selected) {
selected.push(opt.innerHTML);
}
}
input.value = selected.join(', ');
}

disable checkbox when i select

i have a problem in html and javascript. i have tried different approach but everything didnt worked. so this is my sample code.
<select id = "testselect" name = "testselect">
<option> </option>
<option id = "o1" name = "testselect" value = "1" onselect='document.getElementById("os1").disabled = true;'> 1 </option>
<option id = "o2" name = "testselect" value = "2" > 2 </option>
<option id = "o3" name = "testselect" value = "3"> 3 </option>
</select>
<div >
<input id = "os1" type="checkbox" name="othser[]" value="7000" />cb1<br/>
<input id = "os2" type="checkbox" name="othser[]" value="7001"/>cb2<br/>
<input id = "os3" type="checkbox" name="othser[]" value="7002"/>cb3<br/>
</div>
ok, that's the code. what i want to happen is, when i selected o1(option id), os1(checkbox id) must be disabled and when i selected o2(option id), os2(checkbox id) must be disabled, and so on. so can anyone help me?
Try this:
Using plain javascript:
var select;
function changeIt() {
var allCheckboxes = document.querySelectorAll('input[type=checkbox]');
for (var i = 0; i < allCheckboxes.length; i++) {
allCheckboxes[i].removeAttribute('disabled');
}
var value = select.options[select.selectedIndex].value;
var checkBox = document.querySelector('input[id=os' + value + ']');
checkBox.disabled = true;
}
window.onload = function () {
select = document.getElementById('testselect');
select.onchange = changeIt;
changeIt();
}
Demo
Using jQuery:
$('select').change(function () {
$('input[type=checkbox]').removeAttr('disabled');
$('input[id=os' + this.value + ']').attr('disabled', true);
});
Demo
My own suggestion would be to move the event-handling outside of the HTML (for ease of future maintenance and change), and take the following approach:
function disableCheck(event) {
// get the element that was the target of the 'change' event:
var that = event.target,
/* find the option tags, and retrieve the option that was selected
from that collection (nodeList) of elements: */
opt = that.getElementsByTagName('option')[that.selectedIndex];
/* find the element whose 'id' is equal to the 'id' of the 'option'
once the 's' is inserted, and set the 'disabled' property to 'true': */
document.getElementById(opt.id.replace('o', 'os')).disabled= true;
}
// bind the onchange event-handler to the element with the id of 'testselect':
document.getElementById('testselect').onchange = disableCheck;
JS Fiddle demo.
To toggle which elements are disabled (rather than simply increase the number of disabled elements):
function disableCheck(event) {
var that = event.target,
opt = that.getElementsByTagName('option')[that.selectedIndex],
idToFind = opt.id.replace('o','os'),
allInputs = document.getElementsByTagName('input');
for (var i = 0, len = allInputs.length; i < len; i++){
if (allInputs[i].type == 'checkbox') {
allInputs[i].disabled = allInputs[i].id === idToFind;
}
}
}
document.getElementById('testselect').onchange = disableCheck;
JS Fiddle demo.
Well, this is ugly...and suggests I really need to rethink the approach above, however it does work (though it doesn't properly support IE as yet). This uses a trigger function which is fired upon the window.load event which triggers the change event from the select element-node:
function trigger(event, source) {
var newEvent;
if (document.createEvent) {
newEvent = document.createEvent("HTMLEvents");
newEvent.initEvent(event, true, true);
} else {
newEvent = document.createEventObject();
newEvent.eventType = event;
}
newEvent.eventName = event;
if (document.createEvent) {
source.dispatchEvent(newEvent);
} else {
source.fireEvent("on" + newEvent.eventType, newEvent);
}
}
function disableCheck(event) {
var that = event.target,
opt = that.getElementsByTagName('option')[that.selectedIndex],
idToFind = opt.id.replace('o', 'os'),
allInputs = document.getElementsByTagName('input');
for (var i = 0, len = allInputs.length; i < len; i++) {
if (allInputs[i].type == 'checkbox') {
allInputs[i].disabled = allInputs[i].id === idToFind;
}
}
}
window.addEventListener('load', function(){
trigger('change', document.getElementById('testselect'));
});
document.getElementById('testselect').onchange = disableCheck;
JS Fiddle demo.
onselect should go into the select
<script>
function onSelect(obj){
var x = document.getElementsByName("othser[]");
for (var i in x) x[i].disabled = false;
document.getElementById("os"+obj.value).disabled=true;
}
</script>
<select id = "testselect" name = "testselect" onchange='onSelect(this)'>
<option> </option>
<option id = "o1" name = "testselect" value = "1" > 1 </option>
<option id = "o2" name = "testselect" value = "2" > 2 </option>
<option id = "o3" name = "testselect" value = "3"> 3 </option>
</select>
<div >
<input id = "os1" type="checkbox" name="othser[]" value="7000" />cb1<br/>
<input id = "os2" type="checkbox" name="othser[]" value="7001"/>cb2<br/>
<input id = "os3" type="checkbox" name="othser[]" value="7002"/>cb3<br/>
</div>

Categories

Resources