Bug??? with loading data from model to js - javascript

I made a JS function that creates selector tags for the clients of a hotel room. So if my room capacity equals to 4, it creates dynamicly 4 selectors. In my selector tag there are options containing the clients. The options values are the ID of the client, but when I set my options.text to Client's name for example I get an error:
Uncaught ReferenceError: changeFunc is not defined
at HTMLSelectElement.onchange
Here is my function:
<script type="text/javascript">
function changeFunc() {
var elements = document.getElementsByClassName('selector2');
while (elements.length > 0) {
elements[0].parentNode.removeChild(elements[0]);
}
var selector = document.getElementById('selector');
var selectedValue = selector.value;
console.log(selectedValue);
#foreach (var item in Model.Rooms)
{
<text>
if (#item.RoomID == selectedValue)
{
var selectedValue2 = #item.Capacity;
}
</text>
}
var inputContainer = document.getElementById('for-input');
for (var i = 0; i < selectedValue2; i++)
{
var selector2 = inputContainer.appendChild(document.createElement("select"));
selector2.className = "selector2";
#foreach (var item in Model.Clients)
{
<text>
var optionz = document.createElement("option");
optionz.value = #item.ID;
optionz.text = #item.Name; <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
selector2.appendChild(optionz);
</text>
}
}
}
Here is my div that contains all the selectors:
<div id="for-input"></div>
The strange thing is that if I change item.Name to item.ID or item.phoneNumber, it works. So that means it supports integers only for some reason. Then I tried setting the optionz.text to "Hello world" and it worked too!!! That just blew my mind :X
I tought that I have some problem with the model and tried to load the clients into a different selector:
<select>
#foreach (var item in Model.Clients)
{
<option value="#item.Name">#item.Name</option>
}
</select>
It worked too!!!
Where the problem comes from???
Please don't judge me too much, it's my first code in JS! I'm learning it rn :)
Thanks in advance!
Updated! Here is my onchange handler:
<div class="form-group">
<label asp-for="Reservations2.RoomId" class="control-label"></label>
<select asp-for="Reservations2.RoomId" onchange="changeFunc();" class="form-select" id="selector">
#foreach (var item in Model.Rooms)
{
<option value="#item.RoomID">Room #item.RoomID with capacity of#item.Capacity</option>
}
</select>
<span asp-validation-for="Reservations2.RoomId" class="text-danger"></span>
</div>

The solution was so simple! I just needed to put the value in quotes...

Related

How do i display my js variable multiple times on a page

I'm collected a variable from the user, a person name, and storing that in a variable. When I hit next, I want to display the name on several different locations, including a dropdown list. I can get it to display the name outside the dropdown list, but only once.
Here is my html:
Collecting the info
<label>Student Name</label>
<input type="text" name="Student Name" id="kidNameInput">
My Next button
<input type="button" value="Next" class="button" onclick="nextForm()"></input>
Displaying the info
<label>What did the student do well?</label>
<div class="custom-select">
<select name="did-well">
<option value="0"><span class="kid-name"></span> did a great job at…</option>
<option value="1"><span class="kid-name"></span> did this…</option>
<option value="2"><span class="kid-name"></span> did something else…</option>
<option value="3"><span class="kid-name"></span> was good…</option>
</select>
Here is my javascript:
function nextForm() {
var nameInput = document.getElementById("kidNameInput").value;
document.getElementsByClassName("kid-name")[0].innerText = nameInput;
}
I don't know if it helps. but between forms, all I am doing is hiding them. not sure if I need to have them on a seperate html pages or not.
It looks like you're only displaying the variable on index 0 (this first index).
When you perform getElementsByClassName it returns an array like object.
So in your code where you have :
document.getElementsByClassName("kid-name")[0].innerText = nameInput;
You should instead try something like:
let arr = document.getElementsByClassName("kid-name");
for(let i=o; i<arr.length; i++) {
arr[i].innerText = nameInput
}
You're getting only the fist kid-name and not all of them. You need to cycle the result of the function getElementsByClassName
function nextForm() {
var nameInput = document.getElementById("kidNameInput").value;
var x = document.getElementsByClassName("kid-name");
for (var i = 0; i < x.length; i++) {
x[i].innerText = nameInput;
}
};

How do I get javascript to see updated select value?

I have a page with about 100 dropdown menus that I need to pass to another. So, I've put everything in an array that I'm sending via javascript. However, I'm not sure how to get the javascript to see the changed values of the dropdowns before sending. I mocked up some code to give you an idea of the problem. It only sends the value of the dropdown box at the time the page is initialized. Any help would be appreciated.
<select id="mydropdown">
<option value="Milk">Fresh Milk</option>
<option value="Cheese">Old Cheese</option>
<option value="Bread">Hot Bread</option>
</select>
<script>
var data = new Array();
data[0] = document.getElementById("mydropdown").value;
</script>
<form name="data" method="POST" action="passdata1b.php">
<input type="hidden" name="data">
</form>
<script>
function sendData()
{
// Initialize packed or we get the word 'undefined'
var packed = "";
for (i = 0; (i < data.length); i++) {
if (i > 0) {
packed += ",";
}
packed += escape(data[i]);
}
document.data.data.value = packed;
document.data.submit();
}
</script>
<h1>This is what the array contains:</h1>
<ul>
<script>
for (i = 0; (i < data.length); i++) {
document.write("<li>" + data[i] + "</li>\n");
}
</script>
</ul>
Go to passdata1b.php
Sam's answer was good, except..
data[0] = document.getElementById("mydropdown").value;
..that won't work since it's a dropdown menu. Instead get the value of the selected option. Use this instead:
var zeData = document.getElementById("mydropdown");
data[0] = zeData.options[zeData.selectedIndex].value;
Why can't you put this logic:
var data = new Array();
data[0] = document.getElementById("mydropdown").value;
In your sendData() function?
Comment if you need an example, but this should be a pretty easy fix. That way, when you click the link and run sendData(), it will parse the mydropdown value..instead of doing it on page load.

How to select all from a dropdown using ASP/JavaScript/HTML

I have a piece of software that I am working on that allows you to select locations and this shows on a map. I want to add functionality to select all the locations with a button and show the information on the map.
I'm new to coding and therefore haven't really written any code. I have been searching the web but to no avail which is why I came to ask you lovely people on here.
Any advice or links you provide will be greatly appreciated.
function checkAddAllName(mode){
var Name = document.getElementById('select_'+mode+'_ID').options[document.getElementById('select_'+mode+'_ID').selectedIndex].text;
var Name = document.getElementById('select_'+mode+'_ID').options[document.getElementById('select_'+mode+'_ID').selectedIndex].value;
var errorCount = 0;
var Name = 0;
var allStations = document.getElementsByTagName('input');
for (var i=0; i<allNames.length; i++){
if (allNames[i].id.substring(0,10) == 'StationNo_'){
var splitID = allNames[i].id.split("_");
if (splitID[1] == mode){
if (allNames[i].value == addedNameNo){
errorCount = 1;
}
}
}
}
if (errorCount == 0){
addNAme(mode);
} else {
alert(addedName+' has already been added!');
}
}
You are better off doing this using a library like jQuery. It'll take you some time in the beginning to learn, but it'll pay off for the rest of your web programming days.
Assuming your locations are an unordered list of checkboxes like:
<ul id='listId'>
<li><input type="checkbox value="London">London</li>
<li><input type="checkbox value="Paris">Paris</li>
<li><input type="checkbox value="Buenos Aires">Buenos Aires</li>
</ul>
<button id="selectAll">Select all</button>
In jQuery you'd do something like:
$('button#selectAll').on("click",function(){
$('ul#listId > li > input').prop('checked',true);
});
Assuming you mean ordinary single selection drop down like this:
<select id="ddlSelectCountry" onchange="SelectCountry(this);">
<option value="">Please select..</option>
<option value="USA">USA</option>
<option value="France">France</option>
<option value="Spain">Spain</option>
</select>
You can have such button to auto select all non empty items:
<button type="button" onclick="SelectAll('ddlSelectCountry');">Select All</button>​
And the JavaScript for that would be:
function SelectAll(strDropDownId) {
var oDDL = document.getElementById(strDropDownId);
if (!oDDL) {
alert("No such element: " + strDropDownId);
return;
}
for (var i = 0; i < oDDL.options.length; i++) {
if (oDDL.options[i].value.length > 0) {
oDDL.selectedIndex = i;
if (oDDL.change)
oDDL.change();
else if (oDDL.onchange)
oDDL.onchange();
}
}
}
Using jQuery the code can be greatly reduced in length and made more elegant, but that's your choice.
Live test case.

How would I dynamically create input boxes on the fly?

I want to use the value of a HTML dropdown box and create that number of input boxes underneath. I'm hoping I can achieve this on the fly. Also if the value changes it should add or remove appropriately.
What programming language would I need to do this in? I'm using PHP for the overall website.
Here is an example that uses jQuery to achieve your goals:
Assume you have following html:
<div>
<select id="input_count">
<option value="1">1 input</option>
<option value="2">2 inputs</option>
<option value="3">3 inputs</option>
</select>
<div>
<div id="inputs"> </div>
And this is the js code for your task:
$('#input_count').change(function() {
var selectObj = $(this);
var selectedOption = selectObj.find(":selected");
var selectedValue = selectedOption.val();
var targetDiv = $("#inputs");
targetDiv.html("");
for(var i = 0; i < selectedValue; i++) {
targetDiv.append($("<input />"));
}
});
You can simplify this code as follows:
$('#input_count').change(function() {
var selectedValue = $(this).val();
var targetDiv = $("#inputs").html("");
for(var i = 0; i < selectedValue; i++) {
targetDiv.append($("<input />"));
}
});
Here is a working fiddle example: http://jsfiddle.net/melih/VnRBm/
You can read more about jQuery: http://jquery.com/
I would go for jQuery.
To start with look at change(), empty() and append()
http://api.jquery.com/change/
http://api.jquery.com/empty/
http://api.jquery.com/append/
Doing it in javascript is quite easy. Assuming you've got a number and an html element where to insert. You can obtain the parent html element by using document.getElementById or other similar methods. The method assumes the only children of the parentElement is going to be these input boxes. Here's some sample code:
function addInput = function( number, parentElement ) {
// clear all previous children
parentElement.innerHtml = "";
for (var i = 0; i < number; i++) {
var inputEl = document.createElement('input');
inputEl['type'] = 'text';
// set other styles here
parentElement.appendChild(inputEl);
}
}
for the select change event, look here: javascript select input event
you would most likely use javascript(which is what jquery is), here is an example to show you how it can be done to get you on your way
<select name="s" onchange="addTxtInputs(this)" onkeyup="addTxtInputs(this)">
<option value="0">Add</option>
<option value="1">1</option>
<option value="3">3</option>
<option value="7">7</option>
</select>
<div id="inputPlaceHolder"></div>
javascript to dynamically create a selected number of inputs on the fly, based on Mutahhir answer
<script>
function addTxtInputs(o){
var n = o.value; // holds the value from the selected option (dropdown)
var p = document.getElementById("inputPlaceHolder"); // this is to get the placeholder element
p.innerHTML = ""; // clears the contents of the place holder each time the select option is chosen.
// loop to create the number of inputs based apon `n`(selected value)
for (var i=0; i < n; i++) {
var odiv = document.createElement("div"); //create a div so each input can have there own line
var inpt = document.createElement("input");
inpt['type'] = "text"; // the input type is text
inpt['id'] = "someInputId_" + i; // set a id for optional reference
inpt['name'] = "someInputName_" + i; // an unique name for each of the inputs
odiv.appendChild(inpt); // append the each input to a div
p.appendChild(odiv); // append the div and inputs to the placeholder (inputPlaceHolder)
}
}
</script>

How to set selectedIndex of select element using display text?

How to set selectedIndex of select element using display text as reference?
Example:
<input id="AnimalToFind" type="text" />
<select id="Animals">
<option value="0">Chicken</option>
<option value="1">Crocodile</option>
<option value="2">Monkey</option>
</select>
<input type="button" onclick="SelectAnimal()" />
<script type="text/javascript">
function SelectAnimal()
{
//Set selected option of Animals based on AnimalToFind value...
}
</script>
Is there any other way to do this without a loop? You know, I'm thinking of a built-in JavaScript code or something. Also, I don't use jQuery...
Try this:
function SelectAnimal() {
var sel = document.getElementById('Animals');
var val = document.getElementById('AnimalToFind').value;
for(var i = 0, j = sel.options.length; i < j; ++i) {
if(sel.options[i].innerHTML === val) {
sel.selectedIndex = i;
break;
}
}
}
<script type="text/javascript">
function SelectAnimal(){
//Set selected option of Animals based on AnimalToFind value...
var animalTofind = document.getElementById('AnimalToFind');
var selection = document.getElementById('Animals');
// select element
for(var i=0;i<selection.options.length;i++){
if (selection.options[i].innerHTML == animalTofind.value) {
selection.selectedIndex = i;
break;
}
}
}
</script>
setting the selectedIndex property of the select tag will choose the correct item. it is a good idea of instead of comparing the two values (options innerHTML && animal value) you can use the indexOf() method or regular expression to select the correct option despite casing or presense of spaces
selection.options[i].innerHTML.indexOf(animalTofind.value) != -1;
or using .match(/regular expression/)
If you want this without loops or jquery you could use the following
This is straight up JavaScript. This works for current web browsers. Given the age of the question I am not sure if this would have worked back in 2011. Please note that using css style selectors is extremely powerful and can help shorten a lot of code.
// Please note that querySelectorAll will return a match for
// for the term...if there is more than one then you will
// have to loop through the returned object
var selectAnimal = function() {
var animals = document.getElementById('animal');
if (animals) {
var x = animals.querySelectorAll('option[value="frog"]');
if (x.length === 1) {
console.log(x[0].index);
animals.selectedIndex = x[0].index;
}
}
}
<html>
<head>
<title>Test without loop or jquery</title>
</head>
<body>
<label>Animal to select
<select id='animal'>
<option value='nothing'></option>
<option value='dog'>dog</option>
<option value='cat'>cat</option>
<option value='mouse'>mouse</option>
<option value='rat'>rat</option>
<option value='frog'>frog</option>
<option value='horse'>horse</option>
</select>
</label>
<button onclick="selectAnimal()">Click to select animal</button>
</body>
</html>
document.getElementById('Animal').querySelectorAll('option[value="searchterm"]');
in the index object you can now do the following:
x[0].index
Try this:
function SelectAnimal()
{
var animals = document.getElementById('Animals');
var animalsToFind = document.getElementById('AnimalToFind');
// get the options length
var len = animals.options.length;
for(i = 0; i < len; i++)
{
// check the current option's text if it's the same with the input box
if (animals.options[i].innerHTML == animalsToFind.value)
{
animals.selectedIndex = i;
break;
}
}
}
You can set the index by this code :
sel.selectedIndex = 0;
but remember a caution in this practice, You would not be able to call the server side onclick method if you select the previous value selected in the drop down..
Add name attribute to your option:
<option value="0" name="Chicken">Chicken</option>
With that you can use the HTMLOptionsCollection.namedItem("Chicken").value to set the value of your select element.
You can use the HTMLOptionsCollection.namedItem()
That means that you have to define your select options to have a name attribute and have the value of the displayed text.
e.g
California

Categories