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

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;
}
};

Related

Change hidden input field value according to select options

I am trying to write a script for changing the hidden input value according to selected options.
I have hindi data stored on a variable and I need to pick this hindi data according to english data selected in select feild. The select options are working fine so far, but I am unable to fectch the related hindi data.
var stateObject = {
"Bihar": {
"Begusarai": ["Bachhwara", "Bakhari", "Balia", "Barauni", "Begusarai", "Bhagwanpur", "Birpur", "Cheriya Bariyarpur", "Chhorahi", "Dandari", "Garhpura", "Khudabandpur", "Mansoorchak", "Matihani", "Nawkothi", "Sahebpur Kamal", "Samho Akha Kurha", "Teghra"],
},
}
var stateObjectHindi = {
"बिहार": {
"बेगूसराय": ["बछवारा", "बखरी", "बलिया", "बरौनी", "बेगुसराय", "भगवानपुर", "बीरपुर", "चेरिया बरियारपुर", "छौराही", "डंडारी", "गढ़पुरा", "खोदाबंदपुर", "मंसूरचक", "मटिहानी", "नावकोठी", "साहेबपुर कमाल", "साम्हो अखा कुरहा", "तेघरा"],
},
}
window.onload = function() {
var stateList = document.getElementById("stateList"),
stateListHindi = document.getElementById("stateListHindi"),
districtList = document.getElementById("districtList"),
districtListHindi = document.getElementById("districtListHindi"),
blockList = document.getElementById("blockList"),
blockListHindi = document.getElementById("blockListHindi");
for (var country in stateObject) {
stateList.options[stateList.options.length] = new Option(country, country);
}
stateList.onchange = function() {
districtList.length = 1; // remove all options bar first
blockList.length = 1; // remove all options bar first
if (this.selectedIndex < 1) return; // done
for (var state in stateObject[this.value]) {
districtList.options[districtList.options.length] = new Option(state, state);
}
}
stateList.onchange(); // reset in case page is reloaded
districtList.onchange = function() {
blockList.length = 1; // remove all options bar first
if (this.selectedIndex < 1) return; // done
var district = stateObject[stateList.value][this.value];
for (var i = 0; i < district.length; i++) {
blockList.options[blockList.options.length] = new Option(district[i], district[i]);
stateListHindi.value = this.value;
}
}
}
<select name="state" id="stateList">
<option value="" selected="selected">Select State</option>
</select>
<select name="district" id="districtList">
<option value="" selected="selected">Select District</option>
</select>
<select name="block" id="blockList">
<option value="" selected="selected">Select Block</option>
</select>
<br/> State in Hindi: <input type="hidden" class="stateListHindi" id="stateListHindi" name="stateListHindi" value="" /><br/> District in Hindi: <input type="hidden" class="districtListHindi" id="districtListHindi" name="districtListHindi" value="" /><br/>Block in Hindi: <input type="hidden" class="blockListHindi" id="blockListHindi" name="blockListHindi" value="" /><br/>
JSFiddle Demo
Your data structure is perhaps not too well-suited for what you want here. You need to find the corresponding property in both objects, for the first two levels, by their position - so you will have to extract the keys first, and use indexOf to locate them.
So for the state first of all, that would be
var selectedKeyIndex = Object.keys(stateObject).indexOf(this.value);
stateListHindi.value = Object.keys(stateObjectHindi)[selectedKeyIndex];
Extract the keys from the English object, and find the index of the property matching the current selection in there. Then use that index, to extract the corresponding property name from the Hindi object.
Now, for the district, you'll have to do the same thing, but for one more level:
var selectedKeyIndex = Object.keys(stateObject[stateList.value]).indexOf(this.value);
districtListHindi.value = Object.keys(stateObjectHindi[stateListHindi.value])[selectedKeyIndex];
And then for the Blocks, which are in an array, you can select directly by index,
var selectedKeyIndex = stateObject[stateList.value][districtList.value].indexOf(this.value);
blockListHindi.value = stateObjectHindi[stateListHindi.value][districtListHindi.value][selectedKeyIndex];
All of it put together here: https://jsfiddle.net/6g5ad4cz/.
(I made the hidden fields into normal text fields, so that the result can be visually checked straight away.)

Iterating through elements returned by jQuery selector

I have some HTML that's structured more or less like which I want to be able to filter though by row.
<div class="parentElement">
<div class="rowInput">
<input type="checkbox" />
<input type="text" value="demo" />
</div>
<div class="rowInput">
<input type="checkbox" />
<input type="text" value="demo" />
<select>
<option>Value 1</option>
<option>Value 2</option>
</select>
</div>
</div>
I'm able to get the two rows I need with
var row = $('.rowInput');
0: div.row.inputRow
1: div.row.inputRow
However I'm having issues with going through these rows and further and pulling out any information. I've tried a few different methods of looping through the rows however the best I've been able to do is traversing the property list of the elements. What want to do however is go through each element of the div.row.inputRow and pull out the information based on element type so I can store the information by row.
Edit: I was able to get what I wanted with the following code:
for (var i = 0; i < rows.length; i++) {
console.log(rows[i]);
for (var j = 0; j < rows[i].childNodes.length; j++) {
console.log(rows[i].childNodes[j]);
}
}
However I'm getting errors whenever I try to use the jQuery '.is()' on the child nodes I'm returning
Uncaught TypeError: rows[i].childNodes[j].is is not a function
Basically what I'm going for in the end is returning each element with '.inputRow' so I can filter out the input of each row and either store it or discard it based on if the checkbox is selected. The main reason I'm going this route is I couldn't get the input I needed by row with both a 'select' and ':input' selector.
Your code is correct except for the way to get childerens try the following:
var rows = $('.rowInput');
for (var i = 0; i < rows.length; i++) {
console.log(rows[i]);
for (var j = 0; j < $(rows[i]).children().length; j++) {
console.log( $(rows[i]).children()[j]);
}
}
check it here: jsfiddle
Try each() function:
$('.rowInput').each(function() {
var $this = $(this);
var checkbox = $this.find('input[type=checkbox]');
var text = $this.find('input[type=text]');
});
The $(this) refers to each .rowInput element.

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.

Disabling All Form Elements In Selected Div (edited)

I have one large form that is separated into different sections with divs. Each section is within the same form (bigform) and I need to make sure only one section is enabled/editable at a time. And if the user changes sections after entering data into one section, all data would be cleared from the old section before disabling it. The ideal way for me is to have something like this:
<form>
<select name="selector">
<option>Choose Which Div To Enable</option>
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3'>Three</option>
</select>
</form>
<form name="bigform">
<div id="1">
<input type="text">
<select name="foo">
<option>bar</option>
<option>bar</option>
</select>
</div>
<div id="2">
<input type="text">
<select name="foo">
<option>bar</option>
<option>bar</option>
</select>
</div>
<div id="3">
<input type="text">
<select name="foo">
<option>bar</option>
<option>bar</option>
</select>
</div>
</form>
When the user selects option "Two" in the selector form, all form elements in DIVs 1 and 3 would be disabled. I've searched the web for hours but I cannot find a solution. What's the best method to achieve this?
I found this code online that does "almost" what I want but not quite. It 'toggles' the form elements in the given element (el). What I'm trying to do is sort of the opposite of this.
<form>
<select name="selector" onChange="toggleDisabled(document.getElementByID(this.value))>
<option>Choose Which Div To Enable</option>
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3'>Three</option>
</select>
</form>
<script>
function toggleDisabled(el){
try {
el.disabled = el.disabled ? false : true;
}
catch(E){}
if (el.childNodes && el.childNodes.length > 0) {
for (var x = 0; x < el.childNodes.length; x++) {
toggleDisabled(el.childNodes[x]);
}
}
}
</script>
A way to solve it without using a scripting library such as jQuery:
function disableFormFields(container, isDisabled) {
var tagNames = ["INPUT", "SELECT", "TEXTAREA"];
for (var i = 0; i < tagNames.length; i++) {
var elems = container.getElementsByTagName(tagNames[i]);
for (var j = 0; j < elems.length; j++) {
elems[j].disabled = isDisabled;
}
}
}
<select name="selector" onchange="partiallyDisableForm(this)">
<!-- give every option a numeric value! -->
<option value='0'>Choose Which Div To Enable</option>
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3'>Three</option>
</select>
function partiallyDisableForm(selector) {
// don't forget to give your form the ID "bigform"
var form = document.getElementById("bigform");
var parts = form.getElementsByTagName("DIV");
for (var i = 0; i < parts.length; i++) {
var part = parts[i];
// give your form parts the ID "formpart_1" through "formpart_3"
if (part.id.match(/^formpart_\d+$/)) {
// you must implement what to do if selector.value is 0
var isDisabled = (part.id != "formpart_" + selector.value);
disableFormFields(part, isDisabled);
}
}
}
When the user selects option "Two" in the selector form, all form elements in DIVs 1 and 3 would be disabled. So when user submits "bigform", only the values inside div 2 would be submitted.
No. the form will always be submitted as a whole, regardless of what elements were disabled in UI.
If you want to submit only one set of form items, create a separate form for each set.
Its not possible to prevent some input elements from submittng, and it might be safer/easier to do the selective saving on the server side, as it would stop erroneous results being saved if JS broke/was compromised.
You could disable the elements not being submitted and maybe change their name attributes to ensure the values weren't used by the server.
You could also assign a name/value to a submit button, and parse this on the server-side. It would be trivial to use Javascript to set a value n the submit button to tell the server side to only the the required buttons.
So you have N sections with id's 1..N, and you want only section i to be active?
If you put it in that wording, I would code it somewhat like this - mind: my jQuery is not that strong, I'm merely pseudo-jQuerying:
function enable( element, sensitive ) {
//recursively disable this node and it's children
element.disabled = !sensitive;
if( element.childNodes ) {
for( var i = 0; i != element.childNodes.length; ++i ) {
enable( element.childNodes[i], sensitive );
}
}
}
// this function should rely on the structure of your document
// it ought to visit all sections that need to be enabled/disabled
function enableSection( i ) {
$("#bigform > div").each( function( index, element ) {
enable( element, index==i );
});
}
$("#sectionselector").change( function( ) {
// find value of active section
var activesection = $("#sectionselector").value; // or the like
enableSection( activesection );
} );

Search a dropdown

I have this HTML dropdown:
<form>
<input type="text" id="realtxt" onkeyup="searchSel()">
<select id="select" name="basic-combo" size="1">
<option value="2821">Something </option>
<option value="2825"> Something </option>
<option value="2842"> Something </option>
<option value="2843"> _Something </option>
<option value="15999"> _Something </option>
</select>
</form>
I need to search trough it using javascript.
This is what I have now:
function searchSel() {
var input=document.getElementById('realtxt').value.toLowerCase();
var output=document.getElementById('basic-combo').options;
for(var i=0;i<output.length;i++) {
var outputvalue = output[i].value;
var output = outputvalue.replace(/^(\s| )+|(\s| )+$/g,"");
if(output.indexOf(input)==0){
output[i].selected=true;
}
if(document.forms[0].realtxt.value==''){
output[0].selected=true;
}
}
}
The code doesn't work, and it's probably not the best.
Can anyone show me how I can search trough the dropdown items and when i hit enter find the one i want, and if i hit enter again give me the next result, using plain javascript?
Here's the fixed code. It searches for the first occurrence only:
function searchSel() {
var input = document.getElementById('realtxt').value;
var list = document.getElementById('select');
var listItems = list.options;
if(input === '')
{
listItems[0].selected = true;
return;
}
for(var i=0;i<list.length;i++) {
var val = list[i].value.toLowerCase();
if(val.indexOf(input) == 0) {
list.selectedIndex = i;
return;
}
}
}
You should not check for empty text outside the for loop.
Also, this code will do partial match i.e. if you type 'A', it will select the option 'Artikkelarkiv' option.
Right of the bat, your code won't work as you're selecting the dropdown wrong:
document.getElementById("basic-combo")
is wrong, as the id is select, while "basic-combo" is the name attribute.
And another thing to note, is that you have two variable named output. Even though they're in different scopes, it might become confusing.
For stuff like this, I'd suggest you use a JavaScript library like jQuery (http://jquery.com) to make DOM interaction easier and cross-browser compatible.
Then, you can select and traverse all the elements from your select like this:
$("#select").each(function() {
var $this = $(this); // Just a shortcut
var value = $this.val(); // The value of the option element
var content = $this.html(); // The text content of the option element
// Process as you wish
});

Categories