I try to make dynamic inputs, I give labels attribute contenteditable="ture" because if I want to edit content other time, I give for attribute in label and name attribute in input this textContent(label)
function addInput() {
let options = `
<select class="select1">
<option value="">--</option>
<option value="number">number</option>
<option value="text">text</option>
<option value="date">date</option>
<option value="datetime-local">datetime-local</option>
<option value="file">file</option>
<option value="tel">tel</option>
<option value="time">time</option>
<option value="url">url</option>
<option value="month">month</option>
<option value="range">range</option>
<option value="color">color</option>
</select>
<input class="input1" type="text">
<button class="button1">create</button>
`;
document.querySelector('.choose').innerHTML = options;
let button1 = document.querySelector('.button1');
button1.addEventListener('click', function(e) {
e.preventDefault
let select1 = document.querySelector('.select1').value;
let input1 = document.querySelector('.input1').value;
let chooses = [
[select1, input1]
];
chooses.forEach((choose) => {
if (choose !== " ") {
let code = `<div class="relative delete dragthing Nlabel" onclick="addvalue()" ><label for="${choose[1]}" contenteditable="true" class="Vlabel" >${choose[1]}</label><span class="removeElement" onclick="removeElement()"><i class="fa-solid fa-circle-xmark"></i></span><input class="Ninput" name="${choose[1]}" type=${choose[0]} ></div>`;
document.querySelector('.Nform').innerHTML += code;
}
});
});
}
<button onclick="addInput()" class="createElement">create input</button>
<div class="choose"></div>
<div class="Nform" id="dragparent"></div>
my problem in this function frist when I create new input and try to change content, for attribute in label and name attribute in input will change to this content but if create input again and try to change content, for attribute in label and name attribute in input will not change to this content so why my function run one time?
function addvalue() {
let values = document.querySelectorAll('.Vlabel');
console.log(values);
values.forEach(value => {
window.addEventListener('click', () => {
let value2 = document.querySelector('.Vlabel').innerText;
document.querySelector('.Vlabel').setAttribute('for', value2);
document.querySelector('.Ninput').setAttribute('name', value2);
});
});
}
addvalue() should take an argument telling it which DIV it should process. Then it can call methods on that element to find the enclosed Vlabel and Ninput elements.
function addInput() {
let options = `
<select class="select1">
<option value="">--</option>
<option value="number">number</option>
<option value="text">text</option>
<option value="date">date</option>
<option value="datetime-local">datetime-local</option>
<option value="file">file</option>
<option value="tel">tel</option>
<option value="time">time</option>
<option value="url">url</option>
<option value="month">month</option>
<option value="range">range</option>
<option value="color">color</option>
</select>
<input class="input1" type="text">
<button class="button1">create</button>
`;
document.querySelector('.choose').innerHTML = options;
let button1 = document.querySelector('.button1');
button1.addEventListener('click', function(e) {
e.preventDefault
let select1 = document.querySelector('.select1').value;
let input1 = document.querySelector('.input1').value;
let chooses = [
[select1, input1]
];
chooses.forEach((choose) => {
if (choose !== " ") {
let code = `<div class="relative delete dragthing Nlabel" onclick="addvalue(this)" ><label for="${choose[1]}" contenteditable="true" class="Vlabel" >${choose[1]}</label><span class="removeElement" onclick="removeElement()"><i class="fa-solid fa-circle-xmark"></i></span><input class="Ninput" name="${choose[1]}" type=${choose[0]} ></div>`;
document.querySelector('.Nform').innerHTML += code;
}
});
});
}
function addvalue(div) {
console.log("addvalue");
let value2 = div.querySelector('.Vlabel').innerText;
div.querySelector('.Vlabel').setAttribute('for', value2);
div.querySelector('.Ninput').setAttribute('name', value2);
}
<button onclick="addInput()" class="createElement">create input</button>
<div class="choose"></div>
<div class="Nform" id="dragparent"></div>
Related
I have a dropdown list like this:
<select id="box1">
<option value="98">dog</option>
<option value="7122">cat</option>
<option value="142">bird</option>
</select>
How can I get the actual option text rather than the value using JavaScript? I can get the value with something like:
<select id="box1" onChange="myNewFunction(this.selectedIndex);" >
But rather than 7122 I want cat.
Try options
function myNewFunction(sel) {
alert(sel.options[sel.selectedIndex].text);
}
<select id="box1" onChange="myNewFunction(this);">
<option value="98">dog</option>
<option value="7122">cat</option>
<option value="142">bird</option>
</select>
Plain JavaScript
var sel = document.getElementById("box1");
var text= sel.options[sel.selectedIndex].text;
jQuery:
$("#box1 option:selected").text();
There are two solutions, as far as I know.
both that just need using vanilla javascript
1 selectedOptions
live demo
const log = console.log;
const areaSelect = document.querySelector(`[id="area"]`);
areaSelect.addEventListener(`change`, (e) => {
// log(`e.target`, e.target);
const select = e.target;
const value = select.value;
const desc = select.selectedOptions[0].text;
log(`option desc`, desc);
});
<div class="select-box clearfix">
<label for="area">Area</label>
<select id="area">
<option value="101">A1</option>
<option value="102">B2</option>
<option value="103">C3</option>
</select>
</div>
2 options
live demo
const log = console.log;
const areaSelect = document.querySelector(`[id="area"]`);
areaSelect.addEventListener(`change`, (e) => {
// log(`e.target`, e.target);
const select = e.target;
const value = select.value;
const desc = select.options[select.selectedIndex].text;
log(`option desc`, desc);
});
<div class="select-box clearfix">
<label for="area">Area</label>
<select id="area">
<option value="101">A1</option>
<option value="102">B2</option>
<option value="103">C3</option>
</select>
</div>
All these functions and random things, I think it is best to use this, and do it like this:
this.options[this.selectedIndex].text
HTML:
<select id="box1" onChange="myNewFunction(this);">
JavaScript:
function myNewFunction(element) {
var text = element.options[element.selectedIndex].text;
// ...
}
DEMO: http://jsfiddle.net/6dkun/1/
Use -
$.trim($("select").children("option:selected").text()) //cat
Here is the fiddle - http://jsfiddle.net/eEGr3/
To get it on React with Typescript:
const handleSelectChange: React.ChangeEventHandler<HTMLSelectElement> = (event) => {
const { options, selectedIndex } = event.target;
const text = options[selectedIndex].text;
// Do something...
};
Using jquery.
In your event
let selText = $("#box1 option:selected").text();
console.log(selText);
Using vanilla JavaScript
onChange = { e => e.currentTarget.options[e.selectedIndex].text }
will give you exact value if values are inside a loop.
function runCode() {
var value = document.querySelector('#Country').value;
window.alert(document.querySelector(`#Country option[value=${value}]`).innerText);
}
<select name="Country" id="Country">
<option value="IN">India</option>
<option value="GBR">United Kingdom </option>
<option value="USA">United States </option>
<option value="URY">Uruguay </option>
<option value="UZB">Uzbekistan </option>
</select>
<button onclick="runCode()">Run</button>
You'll need to get the innerHTML of the option, and not its value.
Use this.innerHTML instead of this.selectedIndex.
Edit: You'll need to get the option element first and then use innerHTML.
Use this.text instead of this.selectedIndex.
<select class="cS" onChange="fSel2(this.value);">
<option value="0">S?lectionner</option>
<option value="1">Un</option>
<option value="2" selected>Deux</option>
<option value="3">Trois</option>
</select>
<select id="iS1" onChange="fSel(options[this.selectedIndex].value);">
<option value="0">S?lectionner</option>
<option value="1">Un</option>
<option value="2" selected>Deux</option>
<option value="3">Trois</option>
</select><br>
<select id="iS2" onChange="fSel3(options[this.selectedIndex].text);">
<option value="0">S?lectionner</option>
<option value="1">Un</option>
<option value="2" selected>Deux</option>
<option value="3">Trois</option>
</select>
<select id="iS3" onChange="fSel3(options[this.selectedIndex].textContent);">
<option value="0">S?lectionner</option>
<option value="1">Un</option>
<option value="2" selected>Deux</option>
<option value="3">Trois</option>
</select>
<select id="iS4" onChange="fSel3(options[this.selectedIndex].label);">
<option value="0">S?lectionner</option>
<option value="1">Un</option>
<option value="2" selected>Deux</option>
<option value="3">Trois</option>
</select>
<select id="iS4" onChange="fSel3(options[this.selectedIndex].innerHTML);">
<option value="0">S?lectionner</option>
<option value="1">Un</option>
<option value="2" selected>Deux</option>
<option value="3">Trois</option>
</select>
<script type="text/javascript"> "use strict";
const s=document.querySelector(".cS");
// options[this.selectedIndex].value
let fSel = (sIdx) => console.log(sIdx,
s.options[sIdx].text, s.options[sIdx].textContent, s.options[sIdx].label);
let fSel2= (sIdx) => { // this.value
console.log(sIdx, s.options[sIdx].text,
s.options[sIdx].textContent, s.options[sIdx].label);
}
// options[this.selectedIndex].text
// options[this.selectedIndex].textContent
// options[this.selectedIndex].label
// options[this.selectedIndex].innerHTML
let fSel3= (sIdx) => {
console.log(sIdx);
}
</script> // fSel
But :
<script type="text/javascript"> "use strict";
const x=document.querySelector(".cS"),
o=x.options, i=x.selectedIndex;
console.log(o[i].value,
o[i].text , o[i].textContent , o[i].label , o[i].innerHTML);
</script> // .cS"
And also this :
<select id="iSel" size="3">
<option value="one">Un</option>
<option value="two">Deux</option>
<option value="three">Trois</option>
</select>
<script type="text/javascript"> "use strict";
const i=document.getElementById("iSel");
for(let k=0;k<i.length;k++) {
if(k == i.selectedIndex) console.log("Selected ".repeat(3));
console.log(`${Object.entries(i.options)[k][1].value}`+
` => ` +
`${Object.entries(i.options)[k][1].innerHTML}`);
console.log(Object.values(i.options)[k].value ,
" => ",
Object.values(i.options)[k].innerHTML);
console.log("=".repeat(25));
}
</script>
You can get an array-like object that contains the selected item(s) with the method getSelected() method. like this:
querySelector('#box1').getSelected()
so you can extract the text with the .textContent attribute. like this:
querySelector('#box1').getSelected()[0].textContent
If you have a multiple selection box you can loop through array-like object
I hope it helps you😎👍
var selectionlist=document.getElementById("agents");
td2.innerHTML = selectionlist.children[selectionlist.selectedIndex].innerHTML;
ECMAScript 6+
const select = document.querySelector("#box1");
const { text } = [...select.options].find((option) => option.selected);
Try the below:
myNewFunction = function(id, index) {
var selection = document.getElementById(id);
alert(selection.options[index].innerHTML);
};
See here jsfiddle sample
I'm working on a test/quiz and I can't solve a problem.
I like to grab the selected value from a option and print it to the result p.
<div class="add">
<div class="add__container">
<select class="add__type">
<option value="0" id="a01" selected>No</option>
<option value="1" id="a02">Ocassionally</option>
<option value="2" id="a03">Yes</option>
</select>
</div>
</div>
<button class="btn" onclick="myValue()">Results</button>
<p id="result">... </p>
And here is my Javascript code where I'm stucked:
function myValue(){
var e = document.getElementById("s01");
var value = e.options[e.selectedIndex].value;
var text = e.options[e.selectedIndex].text;
document.getElementById('result').innerHTML = e;
};
try this code. I think this code work like you requirement.
function myValue(){
var select = document.getElementsByClassName("add__type")[0].value;
document.getElementById('result').innerHTML = select;
};
<div class="add">
<div class="add__container">
<select class="add__type">
<option value="0" id="a01" selected>No</option>
<option value="1" id="a02">Ocassionally</option>
<option value="2" id="a03">Yes</option>
</select>
</div>
</div>
<button class="btn" onclick="myValue()">Results</button>
<p id="result">... </p>
something more..
I think you want to put the actual text of the selected option in the innerHtml instead of the option DOM element:
document.getElementById('result').innerHTML = text;
Maybe you want this? I added the id "s01" on select.
<div class="add">
<div class="add__container">
<select id="s01" class="add__type">
<option value="0" id="a01" selected>No</option>
<option value="1" id="a02">Ocassionally</option>
<option value="2" id="a03">Yes</option>
</select>
</div>
</div>
<button class="btn" onclick="myValue()">Results</button>
<p id="result">... </p>
<script>
function myValue() {
var e = document.getElementById("s01");
var value = e.options[e.selectedIndex].value;
var text = e.options[e.selectedIndex].text;
document.getElementById('result').innerHTML = text;
};
</script>
// Unimportant stuff
const $ = document;
$.get = $.getElementById;
$.get('theOptions').addEventListener('change', function(event) {
// Get the value from the select-element
$.get('out').innerHTML = 'You selected ' + event.target.value; // Or $.get('theOptions').value
});
<select id="theOptions">
<option value="o1">Option 1</option>
<option value="o2">Option 2</option>
<option value="o3">Option 3</option>
</select>
<span id="out">Nothing selected</span>
I'd like to return and output to a variable a select option that the user selects in a dropdown menu below.
<h3>Cake Size</h3>
<select id="cakeSize">
<option value="6">6" Cake</option>
<option value="8">8" Cake</option>
<option value="10">10" Cake</option>
<option value="12">12" Cake</option>
</select>
<button type="button" id="calc">Calculate</button>
I want to get 6/8/10/12 into a variable.
const calc = document.getElementById('calc');
let cakeSize = document.getElementById('cakeSize');
let value = cakeSize.value;
calc.addEventListener('click', function test(){
return alert(value);
});
Would like to do this initially using a button event listener to trigger the collection of the value.
If you want to alert the selected value, use alert(cakeSize.value). let value = cakeSize.value; will have only the initial select value.
let cakeSize = document.getElementById('cakeSize');
// let value = cakeSize.value;
calc.addEventListener('click', function test() {
return alert(cakeSize.value);
});
<h3>Cake Size</h3>
<select id="cakeSize">
<option value="6">6" Cake</option>
<option value="8">8" Cake</option>
<option value="10">10" Cake</option>
<option value="12">12" Cake</option>
</select>
<button type="button" id="calc">Calculate</button>
I have a form with dropbox with a few options.
I want to change a paragraph according to the selected value in the dropbox, i.e. the selected value will replace the paragraph.
For ex. I have:
<select name="howmanyno1" size=1>
<option value=2 selected>2</option>
<option value=3>3</option>
<option value=4>4</option>
<option value=5>5</option>
</select>
//somewhere below
<p>number</p>`
I need the text "number" be replaced after selecting a value from the dropbox, with the value selected (2,3,4 or 5).
How should I do this?
Thanks.
<select onchange="myFunction()" name="howmanyno1" id="mySelect">
<option value=2 selected>2</option>
<option value=3>3</option>
<option value=4>4</option>
<option value=5>5</option>
</select>
<p id="demo">number</p>`
<script>
function myFunction() {
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
}
</script>
<select name="howmanyno1" id="selectDiv" size=1 onchange="changePara()">
<option value=2 selected>2</option>
<option value=3>3</option>
<option value=4>4</option>
<option value=5>5</option>
</select>
//somewhere below
<p id="changed">number</p>
js code
function changePara(){
var val = document.getElementById("selectDiv").value;
if(val == 2){
document.getElementById("changed").innerHTML = "something";
}
else if(val == 3){
document.getElementById("changed").innerHTML = "something else";
}
// and so on
}
A jQuery based solution
Add an id to your <p> element
<p id="para">number</p>
Use jQuery to select the <select> box
let select = $('select[name="howmanyno1"]')
Create a function for updating the text in <p>
let updateText = function(e) {
$('#para').text("Selected item: " + select.val())
}
And then make the select box listen to the change event
select.on('change', updateText)
I hope this solution will be usefull
var textBlocks = new Array(
'Select from the list to change this box',
'Text block two',
'Text block three');
function changeText(elemid) {
var ind = document.getElementById(elemid).selectedIndex;
document.getElementById("display").innerHTML=textBlocks[ind];
}
</head><body>
<select id="dropDown" onChange="changeText('dropDown');">
<option value="0">1</option>
<option value="1">2</option>
<option value="2">3</option>
</select><br>
<div id="display">Select from the list to change this box</div>
</body></html>
I need your help,
Using javascript, how could I add some sort of data form validation that would be two-fold:
1st Event, [OnKeyUp] attached to all of the input boxes
2nd Event, [OnChange] attached to all of the select boxes
Typical User Scenarios
If there is any data present in any of the input boxes and no selected option values then { enable the search button } else { keep the search button disabled }
If there are any selected option values who’s option value is not null and no data present in all of then { enable the search button } else { keep the search button disabled }
<!DOCTYPE html>
<html>
<head></head>
<body>
<form id="myform">
Cars
<select id="car">
<option value=""></option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br><br>
Fruits
<select id="fruits">
<option value=""></option>
<option value="apple">apple</option>
<option value="banana">banana</option>
<option value="pear">pear</option>
<option value="strawberry">strawberry</option>
<option value="mango">mango</option>
<option value="orange">orange</option>
</select>
<br><br>
Vegetable
<input type="input" id="veggie">
<br><br>
Number
<input type="input" id="number">
<br><br>
<input type="button" value="search" id="search" disabled>
</form>
</body>
</html>
var car=$('#car'); var fruits=$('#fruits');
var veggie=$('#veggie'); var number = $('#number');
$('select').change(function(){
validate();
});
$('input').keyup(function(){
validate();
});
function validate(){
if(($(veggie).val()!='' || $(number).val()!='') &&
$(car).val()=='' && $(fruits).val()==''){
$('#search').prop('disabled',false);
}else if($(veggie).val()=='' && $(number).val()=='' &&
($(car).val()!='' || $(fruits).val()!='')){
$('#search').prop('disabled',false);
}else{
$('#search').prop('disabled',true);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<form id="myform">
Cars
<select id="car">
<option value=""></option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br><br>
Fruits
<select id="fruits">
<option value=""></option>
<option value="apple">apple</option>
<option value="banana">banana</option>
<option value="pear">pear</option>
<option value="strawberry">strawberry</option>
<option value="mango">mango</option>
<option value="orange">orange</option>
</select>
<br><br>
Vegetable
<input type="input" id="veggie">
<br><br>
Number
<input type="input" id="number">
<br><br>
<input type="button" value="search" id="search" disabled>
</form>
</body>
I'm not 100% sure, but it looks like you want to enable the button if only one of the select elements has a value or one of the input elements has a value, but not if both (or neither) do.
If that's the case then this should work, and it allows you you add as many elements to it as you need by adding IDs to the arrays at the top.
https://jsfiddle.net/j7by6bsz/
var selectInputIds = ['fruits', 'car'];
var textInputIds = ['veggie', 'number'];
function setButtonState() {
var hasVal = function(arr) {
for(var i = 0; i < arr.length; i++) {
if(document.getElementById(arr[i]).value) {
return true;
}
}
return false;
};
var hasSelectValue = function () {
return hasVal(selectInputIds);
}
var hasTextValue = function () {
return hasVal(textInputIds);
}
var theButton = document.getElementById('search');
var s = hasSelectValue();
var t = hasTextValue();
theButton.disabled = ((s && t) || (!t && !s)); // you can do this bit smarter, but this is explicit
}
(function attachStuff (arr, evt) {
function listenIn(arr, evt) {
for(var i = 0; i < arr.length; i++) {
document.getElementById(arr[i]).addEventListener(evt, setButtonState);
}
}
listenIn(selectInputIds, 'change');
listenIn(textInputIds, 'keyup');
}())
Your requirements could use some clarification around what happens if both input types have values though.