How can I generate different names for input fields? - javascript

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.

Related

Dynamically add textbox and assign it's value from a function

I want to create n number of textboxes dynamically based upon the user input.
Each textbox must populate with a serial number.Here, what I have tried so far.
function generateSerial(sender,eventArgs){
debugger;
//var rw_Serail = stockin.rw_Serail;
if(eventArgs.get_newValue()!="0"){
if(eventArgs.get_newValue()!=eventArgs.get_oldValue()){
create(eventArgs.get_newValue());
//OpenWindow(null,null,"rw_Serial");
}
}
}
Create will call a function and it's job is to create textboxes and assign a value.
function create(param) {
debugger;
var s= "";
for(var i = 0; i < param; i++) {
s+= `<input type="text" style="width:72%" name="txtSerial" value=${generateLicense()}>`
`<button type="button" style="margin-left: 5px;height: 24px;">Change</button>`; //Create one textbox as HTML
}
document.getElementById("dvserialNo").innerHTML=s;
}
as name suggests generateLicense() will return a serial number..
function generateLicense() {
return "abcd1234Etc..";
}
Now while running this code, I am getting this error..
In chrome
Uncaught TypeError: generateLicense(...) is not a function
In firefox
TypeError: (("<input type=\"text\" style=\"width:72%\" name=\"txtSerial\" value=" + (intermediate value)) + ">") is not a function
Note: I want to create and assign it's value at the same time.
Concatenate the two elements in s+. And, of course, as one of the answers suggested include quotes for value="${generateLicense()}"
s+= `<input type="text" style="width:72%" name="txtSerial" value="${generateLicense()}">`
+ `<button type="button" style="margin-left: 5px;height: 24px;">Change</button>`; //Create one textbox as HTML

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

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

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

Print dynamic Text box value using JQuery

I have a scenario like
for(int i = 0; i < 10; i++)
{
<input type = "text" id="test"+i value="" onchange="getValue(i)">
}
I want to print selected text box value using jquery. I tried below code,....
function getValue(id)
{
var value = $("#test"+id).val();
alert(value);
}
Some how the above code is not working.
if i tried like var value = document.getElementById("test"+id); then it is working.
jsBin demo
var inp = ''; // String will hold all inputs
for(var i=0; i<10; i++){
inp += '<input type="text" id="test'+i+'" value="" />'; // Generate 10 inputs
}
$('body').append( inp ); // All inputs to HTML
$('input[id^="test"]').on('input', function(){
console.log( this.value );
});
You can't just drop raw HTML inside of a JavaScript loop like that. You have to set a string or create an element and append it to the DOM.
"getValue(i)" is a string. The "i" is not the variable i, it is literally a string with the letter i. If you want to concatenate strings and variables you have to do so like this:
var name = "Neil";
var greeting = "Hi, my name is " + name + ", nice to meet you!";

html table editable and non-editable cells with jQuery

Is there a plugin or way to make certain table columns (not rows) editable and others not editable
with jQuery?
I have seen plugins for clicking on a cell to make it editable, but I mean explicitly making a cell/column editable or not.
I have a way of doing it but it feels like a bit of a hack job.
Here is my function for making a column editable:
function isEditable(rowArray, headersArray)
{
var counter = 0;
var notEditable = ['product code', 'product'];
for(i in rowArray){
counter = 0;
data = headersArray[i].toLowerCase();
for(a in notEditable){
if(data == notEditable[a]){
counter++;
}
}
if(counter > 0){
rowArray[i] += 'notEditable';
}
}
return rowArray;
}
it compares the header of the cell to an array of predefined values which = a non-editable column.
Then I build the row:
function buildHTMLTableRow(row, mutable)
{
output = '';
output += '<tr>';
for(var i = 0; i < row.length; i++)
{
value = trim(row[i]);
if(mutable){
index = value.indexOf('notEditable');
if(index != -1){
value = value.substring(0, index);
output += '<td>' + value + '</td>';
}
else{
output += '<td><input size="5" type="text" value="' + value + '" /></td>';
}
}
else{
output += '<td>' + value + '</td>';
}
}
output += '</tr>';
return output;
}
The mutable parameter decides if the row is editable or not, and the indexOf('noteditable') decides for the cell(but pretty much column) from the isEditable function.
Is there a plugin that does this better, or should I just settle with what I have?
Visit this jsFiddle link: Disable Columns
Following is the data flow:
I have created a row Array named "rowsD". When page loads I am populating my table (id=myData) with these rows.
Now creating another array called disableHeaders wherein I am passing the headers,
which you need to disable entire columns.
I am calling function disableFields passing disableHeaders as parameter
In the function, first I am fetching the index of the header whose value is equal to the values in headers array
If I find one, then from Input tag I am extracting the Value attribute using $(this).find('input') selector
Finally I am replacing the current child with Label tag passing the extracted Input tags Value
You may also comment out disableFields(disableHeaders); line to actually see, how table gets rendered initially
Thank you

Categories

Resources