Select a HTML Selection field based on a JavaScript Variable Value? - javascript

I am editing an existing Smarty Template that has JavaScript like below which builds a portion of the page.
In the code snippet of JavaScript below you can see a Value for an HTML Input field is set with this JavaScript variable var priority
var priority = 'Urgent';
e.innerHTML += '<input name="priority_'+num+'" id="priority_'+num+'" size=6 type="text" value="'+priority+'" class="priority">';
In my template file there is many different variables and sections very similar to this one posted above. if i can get help with this one, then i can apply the changes across all my other ones so there is no need to post them all here.
What I need to do is replace this text input field with a Dropdown Selection field and then also have the correct value to be selected based on the value of the var priority variable.
So the new field would look something like this instead of the old text input field shown above...
e.innerHTML += '<select name="priority_'+num+'" id="priority_'+num+'">
<option value="Low">Low</option>
<option value="Medium">Medium</option>
<option value="High">High</option>
<option value="Urgent">Urgent</option>
</select>';
But I would then need to have the value of this JavaScript variable var priority to have the correct selection value SELECTED
I would appreciate any help I can get with this please?
UPDATES
After trying out a couple ideas from the comments I have realized I need to go ahead an post more of my code and explain more as it seems to be a bit more complex than I had thought originally.
So below is a JavaScript function that gets called which inserts a Row of HTML form inputs and selections each time the Function is called. It not only inserts this row into the DOM but if currecnt values are supplied, it then populates the Values for each field as well. The problem is it is currently only text input fields and I am trying to convert a few of the text fields into Selection fields.
<script type='text/javascript'>
var project_tasks = new Array();
var priotities = ['Low', 'Medium', 'Urgent'];
YAHOO.util.Event.onDOMReady(function(){
// code iterates my PHP and calls this for each existing Tasks row to add and
// Load in all the existing Tasks for this record.
add_task_row("","fgsdgsdfjhg","gsdgsdfhjgh","hsdgsdfj","Low","klk");
add_task_row("","sdgsdfgdfg","dfgsdfgsdfg","dfgdsfg","Urgent","hlf");
});
function add_task_row(taskid,name,description,status,priority,type){
var ii = document.getElementById("project_tasks");
var num = document.getElementById("tasks_count").value;
num++;
var e = document.createElement("div");
e.setAttribute('id','task_'+num);
//e.innerHTML = '<input name="taskID_'+num+'" id="taskID_'+num+'" size=0 type="hidden" value="'+taskID+'">';
// Add an ID
e.innerHTML = '<div style="float: left; width: 111px;"><input name="taskid_'+num+'" id="taskid_'+num+'" size=9 type="text" value="'+taskid+'"></div>';
e.innerHTML += '<div style="float: left; width: 400px;"><input name="name_'+num+'" id="name_'+num+'" size=45 type="text" value="'+name+'"></div>';
e.innerHTML += '<div style="float: left; width: 400px;"><input name="description_'+num+'" id="description_'+num+'" size=45 type="text" value="'+description+'"></div>';
e.innerHTML += '<div style="float: left; width: 90px;"><input name="status_'+num+'" id="status_'+num+'" size=5 type="text" value="'+status+'"></div>';
//e.innerHTML += '<div style="float: left; width: 90px;"><input name="priority_'+num+'" id="priority_'+num+'" size=6 type="text" value="'+priority+'" class="priority"></div>';
e.innerHTML += '<div style="float: left; width: 90px;"><select name="priority_'+num+'" id="priority_'+num+'" class="priority"><option value="Low">Low</option><option value="Medium">Medium</option><option value="High">High</option><option value="Urgent">Urgent</option></select></div>';
e.innerHTML += '<div style="float: left; width: 90px;"><input name="type_'+num+'" id="type_'+num+'" size=4 maxlength=6 type="text" value="'+type+'"></div>';
e.innerHTML += '<div style="float: left; width: 30px;"><button type="button" onclick="remove_item_row('+num+')"><img src="index.php?entryPoint=getImage&imageName=id-ff-clear.png"></button></div>';
e.innerHTML += '<br style="clear:both;">';
document.getElementById("tasks_count").value = num;
ii.appendChild(e);
}
What this function does above, is when I click a button to add a new Task, it calls this function and leaves each Function Variable empty which results in a new Task row inserted into teh DOM and each input is empty and ready for me to type in new values.
Now when the page loads, it first iterates over an array of values and call this function for each Tasks in the array, it then sets the Value for each inputs based on the value in the Tasks array.
So you can see this same code works for adding new Tasks rows and editing existing Tasks rows.
I just need to be able to convert some of the text input fields into selection fields and then still be able to set the value for them on existing Tasks records that are loaded.
Hopefully this makes some sort of sense. Thanks for all help!

The approach I'd go for is to create a separate function that generates the select options...exactly the same way you're doing it now by generating the html string, except that this function will "insert" the output html between the opening and closing select tag...
var priorities = ['Low', 'Medium', 'Urgent'];
function createOptions(selectedPriority){
var options = '';
for(var i = 0; i < priorities.length; i++){
options += "<option value='" + priorities[i] + "' "
+ (selectedPriority == priorities[i] ? "selected='selected'" : "")
+ ">" + priorities[i] + "</option>";
}
return options;
}
this is just to give you an idea. You probably don't need the selectedPriority argument since you already have the priority variable which I believe is accessible within this scope. Now, you will run this function when you are generating the select HTML as below...
e.innerHTML += "<select name='priority_" + num + "' id='priority_" + num + "'>" +
createOptions(num) +
"</select>";

Related

How can I generate different names for input fields?

the output
I am working on a HTML form where I am forced to use jQuery so that the user can add rows to the table as much as he wants. The problem is with the name of the inputs fields.
This is my function. The value of the k in the first text field shows just k not a number!
var k = 0;
function myfunction(x) { //x refers to onclick($(this))
alert(k);
k++;
var row = x.closest("tr");
$("<tr><td></td> <td><input name=k value=k style='display:block; ;box-sizing:border-box;width:100%; border:none;');/> </td> </tr>").insertAfter(row);
$("#myform").on("click", "TheSelectorForTheIcon", function() {
var row = x.closest("tr");
$("<tr>…</tr>").insertAfter(row);
})
}
You need to concatenate the value of the k variable in to the HTML string. Also note that some parts of the HTML string are not necessary, such as the closing parenthesis and extra apostrophe. Try this:
function myfunction($x) {
k++;
var $row = $x.closest("tr");
$('<tr><td></td><td><input name="' + k + '" value="' + k + '" style="display: block; box-sizing: border-box; width: 100%; border: none;" /></td> </tr>').insertAfter($row);
$("#myform").on("click", "TheSelectorForTheIcon", function() {
var $row = $x.closest("tr");
$("<tr>…</tr>").insertAfter($row);
})
}
However the simple answer to your question about generating dynamic field names is: don't. Give the inputs the same name and deal with their values as an array on the server side.

How to replace an input box with a dropdown in Vanilla JS

I am trying to replace an input box with Vanilla JS. Currently I am using jquery to do this like so.
column.replaceWith("<select id='" + column[0].id + "' name='" + column[0].id + "' class='" + column[0].className + "'></select>");
I am refactoring all my code into Vanilla JS and this is the last thing I need to do. I have done the document.createElement('select'); and that creates the <select></select> element. I then tried to do;
newEl.innerHTML += '<select id="selBidReceivedIsPM" name="selBidReceivedIsPM">'
+ '<option value="0">AM</option>'
+ '<option value="1">PM</option>';
,
but this doesn't create the id or name. I've been googling and trying things for the last 3 hours and need some help figuring this out.
html:
<label for="columnA5"></label>
<input
type="number"
id="columnA5"
name="columnA5"
class="columnA"
step="any"
>
Something like this should work to create select with options having value and innerHTML.
var select = document.createElement('select');
select.id="selBidReceivedIsPM"
select.name="selBidReceivedIsPM"
var val=2;
var time=["AM","PM"];
for (var i = 0; i<val; i++){
var opt = document.createElement('option');
opt.value = i;
opt.innerHTML = time[i];
select.appendChild(opt);
}
console.log(select)
I think, if DOM element is not created by javascript but rendered You can't "delete" it (in Your case input type="number"...).
You can "replace" it by "hiding" input and place select element on "his" place.
There is example, try it :
function replaceEle() {
var txt=document.getElementById('columnA5');
/*
or You can use querySelectorAll :
var txt=document.querySelectorAll('input[type="number"]');
then You'll get all textboxes in page, and then You have to use for loop
*/
var sel=document.createElement('select'); //create select element
sel.id='selBidReceivedIsPM';
sel.setAttribute('onchange','alert(this.value)');
/*show selected value, or instead alert You can type some JS
function, what gonna do when option is changed */
var opt=document.createElement('option'); //create option element
opt.value=0;opt.innerHTML='AM';
sel.appendChild(opt); //add option element into select element
opt=document.createElement('option');
opt.value=1; opt.innerHTML='PM';
sel.appendChild(opt);
sel.selectedIndex=0; //set default selected value
txt.style.display='none'; //hide input element
txt.parentNode.insertBefore(sel, txt); //insert select element just before input,
}
<input type="number" id="columnA5" value=""/><br>
<input type="button" value="Replace it" onclick="replaceEle();"/>

How do I Separate an Array Value from input to HTML

I'm getting this value from the page source (after the page finished loading), the data is coming from a back-end process that populates a hidden text input on the page. I wish to separate this data and then display it in HTML format.
This is the code from 'View Page Source'
<input name="hiddenUserStats" type="hidden" id="hiddenUserStats" value="
99.0~35.0~8.0~.0~1.0~6.0~3.0~.0~1.0~3.8~1.8~1.0~.0~16.0" />
On the value, I'm assuming that each .0~ separates the true value that I wish to separate and display. Anyone know what would be the best step to separate and display such data? Do I start with separating them in variables?
You can use split() function to separate your stats values.
var value = document.getElementById('hiddenUserStats').getAttribute('value');
var stats = value.split('~');
for (i = 0; i < stats.length; i++)
{
var div = document.createElement('div');
div.innerText = stats[i];
document.body.appendChild(div);
}
<body>
<input name="hiddenUserStats" type="hidden" id="hiddenUserStats" value="
99.0~35.0~8.0~.0~1.0~6.0~3.0~.0~1.0~3.8~1.8~1.0~.0~16.0" />
</body>
Here is another way using native array methods;
document.getElementById('hiddenUserStats')
.getAttribute('value')
.split('~')
.map(function(val, i) {
return '<div>' + i + ': '+ val + '</div>';
})
.forEach(function(el) {
document.body.innerHTML += el;
});

Displaying multiple html text box values in an ascending order [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I am using a HTML page where I have multiple textbox inputs, lets say five for example. I have a submit button. Once I enter all values in the text boxes and hit submit, i want all the values to be displayed in the area below submit button on the document in an ascending order. I want to sort all the values to display as result. I just used an array to test if my concept is right, but no luck. Anyone could help is highly appreciated.
This is the code:
function myFunction() {
var txt = new array[];
var txt[0] = $('input:text[name=text1]').val();
var txt[1] = $('input:text[name=text2]').val();
var txt[2] = $('input:text[name=text3]').val();
var txt[3] = $('input:text[name=text4]').val();
var txt[4] = $('input:text[name=text5]').val();
txt.sort();
for (var i = 0; i < txt.length; i++) {
document.getElementById('txt[i]').value + ' ';
}
}
The .text-1, .text-2, etc are the classes of your input fields. The .val() will get the user input of those once they click on your submit button. The last line creates a new div and appends the user input to the results div.
$('.submit-button').on('click', function() {
aaa = $('.text-1').val();
bbb = $('.text-2').val();
ccc = $('.text-3').val();
ddd = $('.text-4').val();
eee = $('.text-5').val();
$('<div>' + aaa + '<br />' + bbb + '<br />' + ccc + '<br />' + ccc + '<br />' + ddd + '<br />' + eee + '</div>').appendTo('.results-div');
});
Here is a fiddle that does what I think you want done:
http://jsfiddle.net/KjHB3/3/
Here is the HTML code:
<input type="text" name="text1" id="text1" /><br/>
<input type="text" name="text2" id="text2" /><br/>
<input type="text" name="text3" id="text3" /><br/>
<input type="text" name="text4" id="text4" /><br/>
<input type="text" name="text5" id="text5" /><br/>
<input type="button" value="submit" id="submit" />
<div id="result">replace</div>
Here is the javascript code:
$("#submit").click(function() {
// Extract all the values into an array
var valArray = [];
$("input[type=text]").each(function(index, el) {
valArray[index] = jQuery(el).val();
});
// Output list of values (in order they appear in form)
$("#result").html("In order of text box: <ol id='list1'></ol>");
$.each(valArray, function(index, value) {
$("#list1").append("<li>" + value + "</li>");
});
// Output list of values (in sorted order)
$("#result").append("In sorted order: <ol id='list2'></ol>");
valArray = valArray.sort();
$.each(valArray, function(index, value) {
if (value != null && value != "") {
$("#list2").append("<li>" + value + "</li>");
}
});
});
Your code appears to be correct, except for the line document.getElementById('txt[i]').value + ' ';. There's nothing writing the values back to the document.
First, starting with the selector, you need to change 'txt[i]' to 'text'+i, because the browser is looking for an element with id txt[i] and finding nothing, thus doing nothing. Also, you should use jQuery, since it makes everything more concise.
Then, to write back to the document, you need to set the value. What your current code (.value + ' ';) does is it gets a value, then adds it to the string ' ', then the statement ends. What you need to do is to set the value of the string, with jQuery (.val(txt[i]);) or stock Javascript (.value = txt[i];).
So, to conclude, just swap the code inside the for loop in your code with this line:
$("input:text[name=text"+i+"]").val(txt[i]);
Let me break down your code in two part to show why it is not working yet.
function GetInputValues() {
var txt = new array[];
var txt[0] = $('input:text[name=text1]').val();
var txt[1] = $('input:text[name=text2]').val();
var txt[2] = $('input:text[name=text3]').val();
var txt[3] = $('input:text[name=text4]').val();
var txt[4] = $('input:text[name=text5]').val();
txt.sort();
return txt; // added by me to encapsulate getting the values
}
The first part of your function myFunction() is correct. You are using jQuery to get the values of the input boxes and writing the values into an array.
The second part has some mistakes:
for (var i = 0; i < txt.length; i++) {
document.getElementById('txt[i]').value + ' ';
}
The function document.getElementById("lastname") returns the html-element whose id is lastname. So in your for-loop you are trying to get the value but you already have the values in your array txt. On top this 'txt[i]' is only a string. So javascript tries to find an element that matches <... id="txt[i]" ...>. But you do not want to get the values you want to write the values back into the document. Assuming you have a div like this <div id='txt[i]'> ...</div> you could wrhite your code like this:
for (var i = 0; i < txt.length; i++) {
document.getElementById('txt[i]').innerHTML += txt[i];
}
Another way would be to join the array:
var myInputValues = GetInputValues(); // this returns your array txt
document.getElementById('myResult').InnerHTML = myInputValues.join(", ");
This assumes that you have a element with id=myResult for example <div id='myResult'>..</div>
Update to adress issues in your code
Your fiddle has this part:
myFunction(txt) { // <-- function declaration: there is something missing here
var myInputValues = GetInputValues(); // this returns your array txt
document.getElementById('myResult').InnerHTML = myInputValues.join(", ");
} //<--- this is the end of myfunction
}); // <-- these do not belong here
// you never execute myFunction
You have to define the function and later call it. Since your mistakes are so basic i really recommend to start with a tutorial to learn javascript. I can recommend Eloquent JavaScript:
to learn the basics of functions
to understand the basics about the Document-Object Model

Dynamically Load Div Elements and Assign IDs

I understand how to dynamically load HTML, I am having trouble understanding how I load it, assign, and keep track of IDs for elements inside the loaded div.
This is my main block
<div id="add-equip-container">
<div id="add-equip-content">
</div>
<button id="add-equipment">Add More Equipment</button>
<button id="submit-equipment">Submit Equipment</button>
</div>
Now, every time add-equipment is clicked, I want to load the following block into add-equip-content.
<div class="add-equip-form">
<input id="?" type="text" placeholder="Equipment Description..."/></br>
<input id="?" type="text" placeholder="Equipment Number"/></br>
<input id="?" type="text" placeholder="Other Stuff..."/></br>
</div>
Each block would be inserted beneath the previous one loaded. I have no idea how to assign and keep track of the various IDs that will be dished out during this operation. I would love a solution that does not involve jQuery. I am trying to lean vanilla JavaScript before I get into frameworks.
I am sure there may be a question or blog or something on this already, but I just don't know the best keywords to search for. Any time I use "Dynamically Load HTML" in the search keywords, all I get is AJAX Tutorial results.
Thanks in advance for any help!
One solution would be not actually load the HTML, but to create it via Javascript. This would be useful in your case as you are adding the same code to the page, only with different ID's. I would write a function like this:
var form_index = 0;
//elem is the element you are appending to.
function addForm(elem) {
//create the container
var form_container = document.createElement("div");
form_container.className = "add-equip-form";
//description input
var desc = document.createElement('input');
desc.id = "equip-desc-" + form_index;
desc.type = "text";
desc.placeholder = "Equipment Description...";
//Equipment number input
var num = document.createElement('input');
num.id = "equip-num-" + form_index;
num.type = "text";
num.placeholder = "Equipment Number";
//Other
var other = document.createElement('input');
other.id = "equip-other-" + form_index;
other.type = "text";
desc.placeholder = "Other Stuff...";
//append inputs
form_container.appendChild(desc);
form_container.appendChild(num);
form_container.appendChild(other);
//append form
elem.appendChild(form_container);
form_index++;
}
Then, to access your created ID's, all you need to know is the index of the containing div within your parent elem. See here for a javascript solution. Once you have the index, getting the form data is as easy as using your index to query based on ID's.
This should do it. You may or may not need to do the elements.push(content) if you don't need to refer back to these elements in an array. Could just iterate a counter instead.
var add_equip_content = document.getElementById('add-equip-content'),
add_equip_btn = document.getElementById('add-equipment'),
elements = [];
add_equip_btn.addEventListener('click', addEquipment, true);
function addEquipment(event){
var content = document.createElement('div'),
html = '';
content.className = 'add-equip-form';
html += '<input id="equip_' + elements.length + '" type="text" placeholder="Equipment Description..."/></br>';
html += '<input id="equip_' + elements.length + '" type="text" placeholder="Equipment Number"/></br>';
html += '<input id="equip_' + elements.length + '" type="text" placeholder="Other Stuff..."/></br>';
content.innerHTML = html;
add_equip_content.appendChild(content);
elements.push(content);
}

Categories

Resources