Populate an input with the contents of a custom option (data-) attribute - javascript

In the example below, I'm trying to populate an input with the contents of the option.data-foo attribute. I feel like this close... but I've got something back-to-front somewhere... Any thoughts?
My code :
function updateText(type) {
var id = type+'Text';
document.getElementById(id).data-foo = document.getElementById(type).value;
}
<form id="example" name="example">
<select id="sensor" onchange="updateText('sensor')">
<option value="Jval" data-foo="Jfoo">Joption</option>
<option value="Kval" data-foo="Kfoo">Koption</option>
</select>
<br />
<input type="text" value="" id="sensorText" />
</form>

If you're using jQuery then use this:
$('#sensor').change(function() {
$('#sensorText').val( $(this).find('option:selected').data('foo') )
})
$('#sensor').change(function() {
$('#sensorText').val( $(this).find('option:selected').data('foo') )
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="example" name="example">
<select id="sensor">
<option value="Jval" data-foo="Jfoo">Joption</option>
<option value="Kval" data-foo="Kfoo">Koption</option>
</select>
<br />
<input type="text" value="" id="sensorText" />
</form>

What you're going for, is probably this :
var selectField = document.getElementById('sensor');
var textField = document.getElementById('sensorText');
var updateTextField = function() {
textField.setAttribute(
'value',
selectField.options[selectField.selectedIndex].dataset.foo
);
}
// Populate your text field when loading your page
updateTextField();
// Update your text field when an option is selected
selectField.addEventListener('change', updateTextField);
<form id="example" name="example">
<select id="sensor">
<option value="Jval" data-foo="Jfoo">Joption</option>
<option value="Kval" data-foo="Kfoo">Koption</option>
</select>
<br />
<input type="text" value="" id="sensorText" />
</form>
(see also this Fiddle)

You can also resolve it in this way
$("#sensor").on("change", function(){
var $selectedItem = $(this).find(":selected");
var dataValue = $selectedItem.data("foo");
$("#sensorText").val(dataValue);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="example" name="example">
<select id="sensor">
<option value="Jval" data-foo="Jfoo">Joption</option>
<option value="Kval" data-foo="Kfoo">Koption</option>
</select>
<br />
<input type="text" value="" id="sensorText" />
</form>

if you are using jquery:
var value = $('#elementId').attr('data-foo');

Related

Removing datalist option from second input

I have two HTML datalist inputs (for first and second language) that can't be the same. Instead of not accepting the form, I want the first option chosen to be removed dynamically from the second datalist but I can't make anything work with JQuery.
Any suggestions with React are also welcome.
Many thanks!😊
<form autocomplete="on" method="POST">
<input id="fLang" type="text" list="language" onchange="removeLang()" placeholder="First language">
<input id="sLang" type="text" list="language" onchange="removeLang()" placeholder="Second language">
<datalist id="language">
<option value="Chinese">China</option>
<option value="English">United Kingdom</option>
<option value="Russian">Russia</option>
</datalist>
</form>
You can achieve this using jQuery by using two datalist elements and detecting the change in the inputs as follows:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<form autocomplete="on" method="POST">
<input id="fLang" type="text" list="flanguage" placeholder="First language">
<input id="sLang" type="text" list="slanguage" placeholder="Second language">
<datalist id="flanguage">
<option id="fChinese" value="Chinese">China</option>
<option id="fEnglish" value="English">United Kingdom</option>
<option id="fRussian" value="Russian">Russia</option>
</datalist>
<datalist id="slanguage">
<option id="sChinese" value="Chinese">China</option>
<option id="sEnglish" value="English">United Kingdom</option>
<option id="sRussian" value="Russian">Russia</option>
</datalist>
</form>
</body>
<script>
var fRemovedItem;
var sRemovedItem;
$(document).ready(function () {
$('#fLang').on('change', function () {
let first = $('#fLang').val();
if (first != '') {
sRemovedItem = $(`#sLanguage option[value='${first}']`);
sRemovedItem.remove();
} else {
let sDatalist = $("#slanguage");
console.log(sDatalist);
console.log(sRemovedItem);
console.log(sDatalist.append(sRemovedItem));
}
});
$('#sLang').on('change', function () {
let second = $('#sLang').val();
if (second != '') {
fRemovedItem = $(`#fLanguage option[value='${second}']`);
fRemovedItem.remove();
} else {
let fDatalist = $("#flanguage");
console.log(fDatalist.append(fRemovedItem));
}
});
});
</script>
</html>
UPDATE: Removed items never go back if users remove the text in fLang or sLang. This situation was fixed with new code.

How to give action to selected combo box

Hi, i want to use search by id and search by date
<select id="menu">
<option value="<?=site_url('web/execute_search')?>">By Id</a></option>
<option value="<?=site_url('web/execute_searchs')?>">By Date</a></option>
</select>
<input type="text" name="search" />
<input type="submit" value="Submit" />
I have combo box, when i select search by id and submit so it will go to Controller ('web/execute_search') , then if i select date and submit, go to Controller ('web/execute_search').
Try this code:
<select id="menu" onchange="option()">
<option value="1" content="1">By Id</a></option>
<option value="2" content="2">By Date</a></option>
</select>
<input type="text" name="search" />
<input type="submit" value="Submit" />
then here's javascript:
<script>function option(){
var x = document.getElementById("menu").value;
if (x==1){
window.location.href = "execute_search";
}
if (x==2){
window.location.href = "execute_searchs";
}}</script>
Using Javascript
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function findID()
{
var e = document.getElementById("menu");
var clicked = e.options[e.selectedIndex].value;
var text = e.options[e.selectedIndex].text;
if(clicked ==1)
{
window.location.href = "web/execute_search";
}
if (clicked ==2)
{
window.location.href= "web/execute_searchs";
}
alert(clicked);
alert(text);
}
</script>
</head>
<body>
<select id="menu" name="menu">
<option value="1">By Id</option>
<option value="2">By Date</option>
</select>
<input type="text" name="search" />
<input type="submit" value="Submit" onclick="findID();" />
</body>
</html>
used e.options[e.selectedIndex].value; to get the value.
used e.options[e.selectedIndex].text; to get the text, means the way you want to sort.
Hope it will help you!!

How to make a generic Jscript function to work with dynamic form

I have this code:
<script type="text/javascript">
function populate(){
s1 = document.ins_form.servizio.value;
valori = s1.split("|");
document.ins_form.codice.value = valori[0];
document.ins_form.costouno.value = valori[1];
}
</script>
<form action="" method="post" name="ins_form" id="ins_form">
<select name="servizio" id="servizio" onchange="populate()">
<option value="">Choose..</option>
<option value="100|10">choice one</option>
<option value="302|32">choice two</option>
</select>
<input type="text" name="codice" id="codice" readonly="readonly" />
<input type="text" name="costouno" id="costouno" readonly="readonly" />
</form>
This is referring to specific input fields (servizio,codice,costouno) that will be populated by user's choices, with different values, and it works nicely.
I'm not a magician with JScript so I can't find a solution to transform this function in a generic one, to be able and use it on other fields dynamically generated and that would be like: servizio1,codice1,costouno1 and servizio2,codice2,costouno2 and servizio3 ecc...
Hope it's kinda clear, thanks for your help.
You can pass the form elements themselves to the function:
<script type="text/javascript">
function populate(field1, field2, fromDelimitedString){
valori = fromDelimitedString.split("|");
field1.value = valori[0];
field2.value = valori[1];
}
</script>
<form action="" method="post" name="ins_form" id="ins_form">
<select name="servizio" id="servizio" onchange="populate(document.getElementById('codice'),
document.getElementById('costuono'), document.getElementById('servizio').value)">
<option value="">Choose..</option>
<option value="100|10">choice one</option>
<option value="302|32">choice two</option>
</select>
<input type="text" name="codice" id="codice" readonly="readonly" />
<input type="text" name="costouno" id="costouno" readonly="readonly" />
</form>

How to auto Set input values in a form when select an option?

I have a form for example:
<form>
<ul>
<li>
<select name="choose">
<option value="0">1</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</li>
<li><h2>No. Of person</h2></li>
<input type="text" name="ref_person"id="field" value="" />
<li><h2>earning of person:</h2></li>
<input type="text" name="ear_person" id="field" value="" />
</ul>
</form>
so, when I choose option:1 both the input fields must be filled with no. let say, No. of person = 3 and earning of person = $5.
Your question should be as well written as you can make it, including valid, semantic HTML.
Also, a question should contain the code you have tried, an explanation of what you have tried, where it's going wrong and exactly what you expect it to do, including some example input and output.
The following may help. Note that element IDs must be unique and that forms should use semantic markup (e.g. don't use a list to present it, don't put headings inside lists, use labels, group elements using fieldsets, etc.).
You can use the select element's change event to get the value and text of the selected option and display it elsewhere in the form. You can also reference form controls as named properties of the form, which is handy and more straight forward than using getElementById.
In the code, a reference to the select is passed to the function using this. Every form control has a form property that is a reference to the form that it's in. The rest should be easy enough to understand, but please ask if you need other help.
function getPerson(select) {
var form = select.form;
form.ref_person.value = select.options[select.selectedIndex].text;
form.ear_person.value = select.value;
}
<form>
<fieldset><legend>Person and earning</legend>
<label for="personSelect">Select a person
<select name="choose" id="personSelect" onchange="getPerson(this)">
<option value="0">1</option>
<option value="100">2</option>
<option value="500">3</option>
</select>
</label>
<br>
<label for="personNumber">No. Of person:
<input type="text" name="ref_person"id="personNumber"></label>
<label for="personEarning">Earning of person:
<input type="text" name="ear_person" id="personEarning"></label>
</fieldset>
</form>
function getPerson(select) {
var form = select.form;
form.ref_person.value = select.options[select.selectedIndex].getAttribute('per');
form.ear_person.value = select.value;
}
<form>
<fieldset><legend>Person and earning</legend>
<label for="personSelect">Select a person
<select name="choose" id="personSelect" onchange="getPerson(this)">
<option per="3" value="0">1</option>
<option per="9" value="100">2</option>
<option per="27" value="500">3</option>
</select>
</label>
<br>
<label for="personNumber">No. Of person:
<input type="text" name="ref_person"id="personNumber"></label>
<label for="personEarning">Earning of person:
<input type="text" name="ear_person" id="personEarning"></label>
</fieldset>
</form>
Here is a code sample that uses the onchange event to copy values to the textboxes.
<script type="text/javascript">
function selectOnChange(obj) {
var val = obj.options[obj.selectedIndex].value;
var text = obj.options[obj.selectedIndex].text;
document.getElementById("field1").value = val;
document.getElementById("field2").value = text;
}
</script>
</head>
<body>
<div>
<select onchange='selectOnChange(this)' name="choose">
<option value="100">1</option>
<option value="200">2</option>
<option value="300">3</option>
</select>
</div>
<ul><li><h2>No. Of person</h2></li></ul>
<div>
<input type="text" name="ref_person" id="field1" value="">
<ul>
<li><h2>earning of person:</h2></li></ul>
<input type="text" name="ear_person" id="field2" value="" />
</div>
I couldn't get a switch statement to work, so I did it with three if statements, but here is my solution. Fiddle with it yourself to make it as you wish.
<form>
<ul>
<li>
<select name="choose" id="option1" onchange="relatedPrice()">
<option value="0">1</option>
<option value="1">2</option>
<option value="2">3</option>
</select>
</li>
<li><h2>No. Of person</h2></li>
<input type="text" name="ref_person" id="field1" value="" />
<li><h2>earning of person:</h2></li>
<input type="text" name="ear_person" id="field2" value="" />
</ul>
</form>
<script>
function relatedPrice() {
var e = document.getElementById("option1");
var test = e.options[e.selectedIndex].text;
document.getElementById("field1").value = test;
if(test==1) {
document.getElementById("field2").value = 100;
}
if(test==2) {
document.getElementById("field2").value = 200;
}
if(test==3) {
document.getElementById("field2").value = 300;
}
}
</script>

jQuery - reproduce serialize()

I have multiple div elements and each one has a set of form fields (text inputs and selects).
Instead of the name attribute these fields have a rel attribute that has the same value as "name" should have.
How can I reproduce the behaviour of jQuery's serialize (http://api.jquery.com/serialize/) on these fields?
the HTML looks like this:
<div>
<input type="text" rel="title" value="bla" />
<input type="text" rel="count" value="5" />
<select rel="page">
<option value="home">home</option>
<option value="about" selected="selected">about</option>
<option value="404">404</option>
</select>
<input type="hidden" name="serialize_above_fields[]" value="" />
</div>
<div>
<input type="text" rel="title" value="bla" />
<input type="text" rel="count" value="5" />
<select rel="page">
<option value="home">home</option>
<option value="about" selected="selected">about</option>
<option value="404">404</option>
</select>
<input type="hidden" name="serialize_above_fields[]" value="" />
</div>
...
basically I want to produce a hidden input field with all the values of fields within the div it resides (and use rel's as keys), like:
<input type="hidden" name="serialize_above_fields[]" value="title=bla&count=5&page=check2&page=about" />
You can use jQuery's map utility to do that pretty easily.
$('div').each(function() {
var serializedData = $(this).find(':text, select').map(function(i, el) {
return $(el).attr('rel') + '=' + $(el).val();
}).get();
$(this).find('input[type=hidden]').val(serializedData.join('&'));
});
If your input elements are all within a <form></form>, You could try to serialize your form using something like this:
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.rel]) {
if (!o[this.rel].push) {
o[this.rel] = [o[this.rel]];
}
o[this.rel].push(this.value || '');
} else {
o[this.rel] = this.value || '';
}
});
return o;
};

Categories

Resources