How to select an option from javascript/angularjs - javascript

How can I select the <select> tag option from the javascript/Angularjs backend.
Hint: I actually get data from API service, then I fill into a form to make them available for edit. Assume the gender is Male, how can I make the <select> tage becomes Male as it is in databse. So user can update it to Female for example.
Here is my codes:
$scope.Gender = [
{ GenderID: "Mmale", name: "Mmale" },
{ GenderID: "Female", name: "Female" }
];
//Assigning data to select tag. But this did not work for me:
$scope.Gender.name = $scope.users[id].Gender;
$scope.Gender.GenderID = $scope.users[id].Gender;
<select class="form-control" name="Gender" ng-model="GenderID" ng-options="g.GenderID as g.name for g in Gender" required style="width:98px; color:gray">
<option value="" style="" >Gender?</option>
</select>
<input type="button" value="SelectMale()">

Did you mean something like this:
$scope.selectMale = function() {
$scope.GenderId = "Mmale";
}
Working plunker.

if you want to see the selected value you can use ng-change write the code as:
<select class="form-control" name="Gender" ng-model="GenderID" ng-options="g.GenderID as g.name for g in Gender" ng-change="Selectmale(g.GenderID)" required style="width:98px; color:gray">
<option value="" style="" ></option>
</select>
$scope.Selectmale=function(genderId){
console.log(genderId) //this will return the current genderId
}

Related

Pls Advice for Multi select dependent dropdown to display in Select box

The multiselect dependent dropdown code below works perfectly. The issue is that I need this to be displayed in a "Select Option Box," similar to a Pillbox, and when the user clicks on it, it should show a value option in a dropdown from which the user can choose a value from Country and State ..
Need this to be displayed and work like a "Select Option Box," similar to this Example - ( Multiselect → Basic example) Link → https://mdbootstrap.com/docs/standard/extended/multiselect/#example2
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="form-signin" method="post" id="serchform" action="search-profile-result.php?page_id=1">
<label for="country">Country</label>
<select class="form-control" id="country" name="country[]" required="required" multiple>
<option value="USA" label="USA">USA</option>
<option value="UK" label="UK">UK</option>
<option value="Canada" label="Canada">Canada</option>
</select>
<label for="state">State</label>
<select id="state" name="state[]" class="form-control" required="required" multiple>
<option disabled>Select Country First</option>
</select>
</form>
<script>
$(function() {
//Populate an Object: { Country: [ States... ] }
var states = {};
states['USA'] = new Array('Alabama', 'Alaska', 'Arizona', 'Other');
states['UK'] = new Array('Aberdeenshire', 'Angus', 'Antrim', 'Other');
states['Canada'] = new Array('Alberta', 'British-Columbia', 'Manitoba', 'Other');
$("#country").change(function() {
// Array Variable to contain all selected
var selected = [];
// Iterate all selected items
$.each($(this).val(), function(i, country) {
selected = selected.concat(states[country]);
});
// Remove previous options
$("#state > option").remove();
if (selected.length === 0) {
// Add placeholder and Stop
$("#state").append("<option disabled>Select Country First</option>");
return false;
}
selected.sort();
// Populate Options
$.each(selected, function(i, state) {
$("<option>").html(state).appendTo("#state");
});
});
});
</script>

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>

JQuery use input text to preselect dropdown box

With only a rudimentary knowledge of JQuery and Javascript, this is killing me. Essentially I want to have a drop-down list autoselect when certain text is entered in the input box.
eg. "Foo" is a "Category4" item, so the select box should choose option 19 automatically if someone types Foo in the input box. "Bar" is a "Category7" item, so the select box should choose option 8 is someone types Bar in the input box.
The reason this isn't hardcoded is because the user will still have the option to recategorize these items if they see fit. ie. Normally "Bar" is a "Category7" item, so the script should automatically select option 8, but the user can change "Bar" to be a "Category1" item by manually selecting it in the dropdown box, and the script shouldn't overwrite the manual selection.
I've scrounged the script below that lets me type in the name of the Category in the input box and have it populate the dropdown, but I can't get to the next step of taking the input, comparing it to a list of predefined responses and using that to populate the dropdown.
<p id="demo"></p>
<input type="text" id="input" placeholder="input">
<select id="category">
<option value="categoryplaceholder">Category</option>
<option value="5">Category1</option>
<option value="22">Category2</option>
<option value="3">Category3</option>
<option value="19">Category4</option>
<option value="23">Category5</option>
<option value="25">Category6</option>
<option value="8">Category7</option>
</select>
<input type="submit" value="submit">
$(document).ready(function() {
$("#input").change(function() {
var val = $("#input").val();
$("#category > option").each(function() { //Run through the loop of each option
if (this.text.indexOf(val) >= 0) { //Find if the string present as substring
$("#category > option").removeAttr("selected"); //Remove the existing selected option
$(this).attr("selected", "selected"); //Select this matching option as selected
return false; //Return after first match is found
}
});
});
});
Super grateful for any help!
https://jsfiddle.net/chuckler/w52kfpcy/
You can use an object to hold your words and its category
$(document).ready(function() {
var Obj = [
{
word : 'FOO',
category : '19'
},
{
word : 'Bar',
category : '8'
},
];
$("#input").on('change' , function() {
var val = $("#input").val();
$.each(Obj , function(i , v){
if(v.word.toLowerCase().trim() == val.toLowerCase().trim()){
$('#category').val(v.category);
return false;
}
})
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="demo"></p>
<input type="text" id="input" placeholder="input">
<select id="category">
<option value="categoryplaceholder">Category</option>
<option value="5">Category1</option>
<option value="22">Category2</option>
<option value="3">Category3</option>
<option value="19">Category4</option>
<option value="23">Category5</option>
<option value="25">Category6</option>
<option value="8">Category7</option>
</select>
<input type="submit" value="submit">
Take in consider:
Input .change event will fire after focus out something like blur
Use .text() to use the option text instead of its value
Use .trim() to remove any white-spaces left/right
Use .toLowerCase() for letters case sensitive
If you need real-time change you can use .on('input' , function(){....}) instead of .change()
Another way you can go with jquery find the method
for more details Click here
$(document).ready(function() {
var Obj = [
{
word : 'FOO',
category : '19'
},
{
word : 'Bar',
category : '8'
},
{
word : 'Prashant',
category : '25'
},
];
$("#input").on('change' , function() {
var val = $("#input").val();
var oFindObj = Obj.find(x=>x.word.toLowerCase().trim()==$.trim(val.toLowerCase()));
if(oFindObj!=undefined){
$("#category").val(oFindObj.category);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="demo"></p>
<input type="text" id="input" placeholder="input">
<select id="category">
<option value="categoryplaceholder">Category</option>
<option value="5">Category1</option>
<option value="22">Category2</option>
<option value="3">Category3</option>
<option value="19">Category4</option>
<option value="23">Category5</option>
<option value="25">Category6</option>
<option value="8">Category7</option>
</select>
<input type="submit" value="submit">

vlookup-like javascript to map input value from one field to another

I am just starting html/javascript, and attempting to create a simple form that populates a specific "Customer Code" when a "Customer Name" is selected from an input list (behaving like an excel vlookup). The examples I found on stackoverflow all resulted in alert windows, but I would like the value to populate in the form.
Here's my html snippet for the Customer Name dropdown list:
<select id="customername">
<option></option>
<option>Doe Inc</option>
<option> Smith LLC </option>
<option> Rogers and Co </option>
Here's the customername to customercode mapping:
Doe Inc = 276. Smith LLC = 852. Rogers and Co = 552.
I would like the customercode to update to the respective customername whenever the customername is updated (without the need for a button), as this is part of a larger form that will an Submit button (in other words, I don't want users to have to click "Submit" to retrieve the customercode, then "Submit" again later in the form).
Thanks!
In order to be included in a form submission, your form controls need to successful controls, which at the simplest means they need a name="" value:
<select id="customername" name="customername">
<option></option>
<option>Doe Inc</option>
<option> Smith LLC </option>
<option> Rogers and Co </option>
</select>
If what you actually care about submitting is the customercode, and the customername is just the "friendly" version, add the value attribute to your options, and rename the select appropriately:
<select id="customercode" name="customercode">
<option value="">Select one...</option>
<option value="276">Doe Inc</option>
<option value="852">Smith LLC </option>
<option value="552">Rogers and Co </option>
</select>
If you want both "values" to be visible on the form and included in the form submission, you could use a data- attribute to sync a readonly input:
<select id="customername" name="customername">
<option data-value="">Select one...</option>
<option data-value="276">Doe Inc</option>
<option data-value="852">Smith LLC </option>
<option data-value="552">Rogers and Co </option>
</select>
<input type="text" name="customercode" id="customercode" readonly />
Then use some JavaScript to sync them:
var select = document.getElementById('customername');
select.onchange = function(e) {
var value = select.options[select.selectedIndex].dataset.value;
var input = document.getElementById('customercode');
input.value = value;
}
Example jsFiddle: https://jsfiddle.net/27jx0q3a/3/
Some links, to help:
W3C: Successful controls
MDN: Using data attributes
I hope this is what you were looking for.
Basically, I used an array to format your numbers, then used the onchange onto the select element and waited for a change. When a change occurs, I fire an event and Javascript gets the values of the field, compares them with the array and returns based on the selected value.
Please refer to Tieson T. Reply, has way more explanations and different approaches for static html!
var drop_down = document.getElementById("customername");
var result = document.getElementById("result");
var list_array = {
"": "Please Select A Value",
"Doe Inc": 276,
"Smith LLC": 852,
"Rogers and Co": 552
}
function change_value() {
if (list_array[drop_down.value]) {
result.innerHTML = list_array[drop_down.value];
}
}
<select id="customername" onchange="change_value()">
<option></option>
<option>Doe Inc</option>
<option>Smith LLC</option>
<option>Rogers and Co</option>
</select>
<span id="result"></span>

Bind select with array of objects and display details when item is selected from select tag

I have an array
$scope.items= [
{ name: "Name1", email: "email1", password: "pas1" },
{ name: "Name2", email: "email2", password: "pas2" }
];
I want to display email value in a select tag. I am using following code but its not working. I want first item as 'Select' :
<select id="idItem">
<option value="-1" selected="selected">Select</option>
<option ng-repeat="o.email as o.email for o in items" value="{{o.email}}"> {{o.email}}
</option>
</select>
Also user can select multiple items. When user selects multiple emails from select box, message box should popup displaying Name and password of selected users.
<select id="idItem" >
<option value="-1" selected="selected">Select</option>
<option ng-repeat="item in items" value="{{item.email}}"> {{item.email}}
</option>
</select>
I think this would work....if it doesn't plz provide your plunkr url next time
I would prefer to use ng-options if you already have a json object containing all items. Further you need to use multiple="true" for multi-select and a ng-model to store the selected results
<select id="idItem" multiple="true" ng-model="selectedItems"
ng-options="item.email for item in items">
</select>
Then you can create a messageBox which displays the selectedItems if you want

Categories