textbox values on change - javascript

I have three textboxes with the same id's in a table. I also have one dropdown on top of the table. While changing the dropdown I need to set the textbox values as same as the dropdown value.
I used the following code and I am able to change only the first textbox, others are not getting values.
function myHome() {
var zoneId = $("#funderIds").val();
$("#funder").val($("#funderIds").val());
}
<select id="funderIds" name="funderIds" onchange="myHome()" style="width: 25%;">
<option value="0">--Select--</option>
<option value="3">option1</option>
<option value="5">option2</option>
<option value="6">option3</option>
</select>
<input type="text" name="funder" id="funder" value="">
<input type="text" name="funder" id="funder" value="">
<input type="text" name="funder" id="funder" value="">
Can anyone give some advise on where I am making a mistake?

It is invalid to use same ID for more than one element, it should be unique throughout the document, thus use class instead!
ID's are unique
Each element can have only one ID
Each page can have only one element with that ID
Classes are NOT unique
You can use the same class on multiple elements.
You can use multiple classes on the same element.
Change your code to:
function myHome() {
var zoneId = $("#funderIds").val();
$(".funder").val($("#funderIds").val());
}
<select id="funderIds" name="funderIds" onchange="myHome()" style="width:25%;">
<option value="0">--Select--</option>
<option value="3">option1</option>
<option value="5">option2</option>
<option value="6">option3</option>
</select>
<input type="text" name="funder-1" id="funder-1" class="funder" value="">
<input type="text" name="funder-2" id="funder-2" class="funder" value="">
<input type="text" name="funder-3" id="funder-3" class="funder" value="">

Id has to be unique, try name instead with min changes:
function myHome() {
var zoneId = $("#funderIds").val();
$("input[name=funder]").val(zoneId);
}
Edited:
To get option text, use :selected:
function myHome() {
var zoneId = $("#funderIds option:selected").text();
$("input[name=funder]").val(zoneId);
}

IDs are unique identifier,they should always be unique. If you have multiple elements with same ID, ID selector ($(".funder") in your case) will return the object of first element only.
You can rather use same class and use class selector to target all the element.
HTML:
<input type="text" name="funder" class="funder" value="">
<input type="text" name="funder" class="funder" value="">
<input type="text" name="funder" class="funder" value="">
JS:
function myHome() {
var zoneId = $("#funderIds").val();
$(".funder").val(zoneId );
}

function myHome() {
var zoneId = $("#funderIds").val();
$(".funder").val(zoneId);
}
<select id="funderIds" name="funderIds" onchange="myHome()" style="width:25%;">
<option value="0">--Select--</option>
<option value="3">option1</option>
<option value="5">option2</option>
<option value="6">option3</option>

Related

How to add more inputs depend dropdown values (PHP, JS)

so I want to add some input based on the option value from the drop down that will be selected. For example, the dropdown looks like this:
<form action="#" method="post">
<select name="job" id="job" >
<option value="">position</option>
<option value="1">Teacher</option>
<option value="2">Principal</option>
<option value="3">Staff</option>
</select>
</form>
and if the selected value is number 1 or teacher, it will display new input like this below it:
<input type="number" name="student" id="student">
<input type="Text" name="class" id="class">
if you guys know how to make it, maybe you can help me with this please, either using php or js because I've been stuck with this problem for a long time.
There are many different ways to achieve what you want depends on what framwwork you are using.
For
vanilla JS: onchange to control css OR append html.
jQuery: $("#class").hide() / .show();
Angular: ngIf
vueJs: v-if / v-show
etc...
In JS you can do that by adding change event listener to the <select></select> element;
and each time the selected <option></option> changes you should make all inputs hidden then make the ones you want visible.
Example:
const select = document.getElementById('job');
select.addEventListener('change', function() {
// returns the selected option's value
const selectedOption = select.value;
// makes all inputs hidden each time the selected option changes.
document.querySelectorAll('input').forEach(input => input.style.display = "none");
// for 1st parameter, pass the option value.
// for 2nd parameter, pass an array of ids of the inputs you want to make them visible.
const setInputs = (state, id) => {
if (selectedOption === state) {
(id.sup ? id = [id] : id);
id.forEach(i => {
try {
document.getElementById(i).style.display = 'block';
} catch (error) {
console.error(`#${i} doesn't exists!`)
}
});
}
}
/* if the selected option's value is 1(Teacher),
The "student" and "class" inputs will be visible. */
setInputs('1', ['student', 'class']);
/* if the selected option's value is 2(Principal),
The "id" and "principal" inputs will be visible. */
setInputs('2', ['id', 'principal']);
/* if the selected option's value is 3(Staff),
The "name" input will be visible. */
/* if you want to show just one input,
don't need to pass an array as 2nd parameter
just pass a string */
setInputs('3', 'name');
});
/* Makes all inputs hidden by default */
input {
display: none;
}
<form action="#" method="post">
<select name="job" id="job">
<option selected hidden disabled>Position</option>
<option value="1">Teacher</option>
<option value="2">Principal</option>
<option value="3">Staff</option>
</select>
<input type="number" name="student" id="student" placeholder="Student">
<input type="Text" name="class" id="class" placeholder="class">
<input type="number" name="id" id="id" placeholder="ID">
<input type="number" name="principal" id="principal" placeholder="Principal">
<input type="Text" name="name" id="name" placeholder="Name">
</form>
before that, set the style of input is hide, then You can try onchange on select, Which is get the value of select. then proceed to show the hide input.
const job = document.getElementById("job");
let add = document.getElementsByClassName("addEx");
job.addEventListener("change",function() {
if (this.value == 1) {
for (let i = 0; i < add.length; i++) {
add[i].style.display = 'block';
}
}
else {
for (let i = 0; i < add.length; i++) {
add[i].style.display = 'none';
}
}
});
.addEx {
display:none;
}
<form action="#" method="post">
<select name="job" id="job" >
<option value="">position</option>
<option value="1">Teacher</option>
<option value="2">Principal</option>
<option value="3">Staff</option>
</select>
<input type="number" name="student" id="student" class="addEx">
<input type="Text" name="class" id="class" class="addEx">
</form>
You can use like this:
jQuery(document).ready(function() {
$('#job').change(function() {
let job = $('#job').val();
if (job == '1') {
$('#sampleBox').show();
} else {
$('#sampleBox').hide();
}
});
});
#sampleBox {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="job" id="job">
<option selected hidden disabled>Position</option>
<option value="1">Teacher</option>
<option value="2">Principal</option>
<option value="3">Staff</option>
</select>
<div id="sampleBox">
<input type="number" name="student" id="student">
<input type="Text" name="class" id="class">
</div>

Html select onchange get custom attribute value set to other input value

onchange I want to get the select option custom attribute and set to the other input's value. Somehow I cannot get the course_price in the input onchange of the select. It only shows the first option value in the input only.
function selectFunction(e) {
var value1 = $("#test").data('typeid'); //to get value
document.getElementById("money").value = value1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control" onchange="selectFunction(event)">
<option id="test" data-typeid="<?php echo $row1['course_price']?>"
value="<?php echo $row1['course_id']?>"><?php echo $row1['course_name']?>
</option>
</select>
<input type="number" value="" id="money" class="form-control">
The issue is because the data-typeid attribute is on the selected option, not the select, so your jQuery code is looking at the wrong element. You can fix this by using find() and :selected to get the chosen option before reading the data attribute from it.
Also note that on* attributes are very outdated. You should be using unobtrusive event handlers, something like this:
$(function() {
$('select.form-control').change(function() {
var typeId = $(this).find('option:selected').data('typeid');
$("#money").val(typeId);
}).change();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control">
<option data-typeid="1111" value="courseId1">courseName1</option>
<option data-typeid="2222" value="courseId2">courseName2</option>
</select>
<input type="number" value="" id="money" class="form-control">
In your question you are using #test which is id for all options and so it will always consider first occurance of id test. So do not use same id multiple times on the same DOM, change it to class="test" if you need it, otherwise, you need to target the selected option, and it will not need any id or class. Check here:
var type_id = $('select option:selected').attr('data-typeid');
and assign the variable to input box:
document.getElementById("money").value =type_id;
So the entire updated function will be like this:
function selectFunction(e) {
var type_id = $('select option:selected').attr('data-typeid'); //to get value
document.getElementById("money").value =type_id;
}
Another way to make it:
$(document).on('change', 'select.form-control', function() {
var r = $('select.form-control option[value="'+$(this).val()+'"]').attr("data-typeid")
$("#money").val(r)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control">
<option selected disabled>-- Select one --</option>
<option data-typeid="1111" value="courseId1">courseName1</option>
<option data-typeid="2222" value="courseId2">courseName2</option>
</select>
<input type="number" value="" id="money" class="form-control">

how to get value from array of selectbox inputs in jquery

On button click i want to fetch selected value of multiple select boxes. i can able to fetch value from array of textboxes but im not able to get select box value. it returns empty array.
$("#add_user_button").click(function(){
var username=[];
$("input[name=username]").each(function(){
username.push($(this).val());
});
var usertype=[];
$("input[name=usertype]").each(function(){
usertype.push($(this).val());
});
var ajaxdata={"UserName":username,"UserType":usertype};
console.log(JSON.stringify(ajaxdata));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div id="user_group">
<input type="text" id="user_username" placeholder="User Name" name="username">
<select id="user_usertype" name="usertype">
<option value="1">Admin</option>
<option value="2">Normal</option>
</select>
</div>
<div class="clone_user_input"><div id="user_group_1">
<div class="form-group">
<input type="text" id="user_username" placeholder="User Name" name="username">
<select id="user_usertype" name="usertype">
<option value="1">Admin</option>
<option value="2">Normal</option>
</select>
</div>
</div>
<button id="add_user_button">Add User</button>
Select is not input. Use:
var usertype=[];
$("select[name=usertype]").each(function(){
usertype.push($(this).val());
});
Also note that you have duplicate IDs for elements. IDs should be always unique. You can rather use same class names as an alternative to this.

Value of selected <datalist> item [duplicate]

This question already has answers here:
Show datalist labels but submit the actual value
(6 answers)
Closed 7 years ago.
I am using a <input type='text'> Element together with a <datalist> to provide user name suggestions for a form. Everything works as expected and all my user show up.
However, when the user submits the form I would like select the right user in my data storage based on the input. Unfortunately, names are not unique and there is a chance for duplicates. To avoid this, all my users have a unique ID that is also part of the <datalist>'s <options> tags.
Is there any way I can read anything else but the input's text value? Is there a reference to the selected datalist element? Can I retrieve a user's id based on the text input?
<input type="text" class="form-control" name="userName" placeholder="Type a user's name" value="" list="user-datalist" required autofocus>
<datalist id="user-datalist">
<option id="53c911ea609252c600632dfe" value="Mr Smith">Mr Smith</option>
<option id="53c911ea60925sdfs4e444eg" value="John Snow">John Snow</option>
<option id="53c911ea6034534535k345th" value="John Snow">John Snow</option>
<option id="53c911ea60925234234234er" value="Mickey Mouse">Mickey Mouse</option>
</datalist>
As you said name are not unique. so i have added a duplicate name to your datalist.
<input type="text" class="form-control" name="userName" placeholder="Type a user's name" value="" list="user-datalist" required autofocus>
<datalist id="user-datalist">
<option id="53c911ea609252c600632dfe" value="Mr Smith">Mr Smith</option>
<option id="53c911ea60925sdfs4e444eg1" value="John Snow">John Snow</option>
<option id="53c911ea60925sdfs4e444eg2" value="John Snow">John Snow</option>
<option id="53c911ea60925234234234er" value="Mickey Mouse">Mickey Mouse</option>
</datalist>
<input type="button" id="sub" value="sub"/>
and getting the id of name
$('#sub').on('click',function(){
var g=$('input[type="text"]').val();
var id = $('#user-datalist').find('option').filter(function() { return $.trim( $(this).text() ) === g; }).attr('id');
alert(id);
});
DEMO
try this (JQuery AutoComplete):
dont forget to reference Jquery.js and JqueryUI.js on your project
HTML
<input id="input_autocomplete" type="text" class="form-control" name="userName" placeholder="Type a user's name" value="" required autofocus>
<datalist id="user-datalist">
<option id="53c911ea609252c600632dfe" value="Mr Smith">Mr Smith</option>
<option id="53c911ea60925sdfs4e444eg" value="John Snow">John Snow</option>
<option id="53c911ea6034534535k345th" value="John Snow">John Snow</option>
<option id="53c911ea60925234234234er" value="Mickey Mouse">Mickey Mouse</option>
</datalist>
JAVASCRIPT AND JQUERY
function GetValues() {
$list = [];
$('#user-datalist').children().each(function () {
var value = $(this).val();
var id = $(this).attr('id');
var item = {
id: id,
value: value
};
$list.push(item);
});
return $list;
}
$(document).ready(function () {
$('#input_autocomplete').autocomplete({
source: GetValues(),
change: function (event, ui) {
alert(ui.item.id)
}
});
});

Use created attribute with javascript in select list

im trying to access an attribute that i created in a select list.
<script language="JavaScript">
function updateUrl()
{
var newUrl=document.getElementById('test').car;
alert(newUrl);
}
</script>
<input type="text" id="test" car="red" value="create Attribute test" size="40"/>
<input type="button" value="submit" onclick="updateUrl();">
it keep giving me undefined. how do i get the string red from attribute car?
edit. i tried it with the select list it alerts null now
<select name= "test" id= "test" onChange= "updateUrl()">
<option value="1" selected="selected" car="red">1</option>
<option value="2" car="blue" >2</option>
<option value="3" car="white" >3</option>
<option value="4" car="black" >4</option>
</select>
Try this:
var newUrl = document.getElementById('test').getAttribute('car');
EDIT
For the <select>, you have to look into the selected <option> element, not the <select> itself:
var select = document.getElementById('test');
select.options[select.selectedIndex].getAttribute('car');

Categories