Javascript unable to extract value of text field in Table - javascript

I have a table that has n number of rows and the 8th and the 9th cells are editable test fields. I need to extract the value of these fields using Javascript and HTML DOM. I have tried different methods but whenever I alert it I get &nbsp or nothing at all as the alert content.
Following is the creation statements:
//Input Fields
for(var i=1; i<=mmrows.length-3; i++)
{//mmrows is the source
var input1 =document.createElement('input');
var input2 =document.createElement('input');
input1.setAttribute("type", "Text");
input2.setAttribute("type", "Text");
//input1.id='Inp1'.concat(i);// Tried to assign ID dynamically
//input2.id='Inp2'.concat(i);
input1.id='Inp1';
input2.id='Inp2';
input1.onkeypress=function(){
return isNumberKey(arguments[0]);
}//for validation
var t1=document.createElement("td");
t1.appendChild(input1);
valrows[i+1].cells[8].appendChild(t1);
var t2=document.createElement("td");
t2.appendChild(input2);
valrows[i+1].cells[9].appendChild(t2);
}
I am trying to extract the values in another function and tried the following:
var cells=document.getElementsByTagName('td');
alert(cells.length);
alert(cells[8].innerText);
alert(cells[8].innerHTML);
alert(trim(valrows[i].cells[8].innerHTML));
alert(trim(valrows[i].cells[9].innerHTML));
var str='Inp1'.concat(i);
var str1='Inp2'.concat(i);
alert(document.getElementsById(str).value); //Dynamic ID
alert(document.getElementsById(str1).value);
var tblcells = valrows[i].cells;
alert(tblcells);
for(var j=0; j<tblcells.length; j++)
{
alert(tblcells[j].firstElementChild.value);
} ​
Please tell me what change I need to make inorder to get the text field value.

I have solved this! Actually it was a mistake by myself; i tried accessing the text values by saying getElement(s)ById - no s required.
so i was able to assign 'id's to these text cells dynamically by using the loop variable i and accessing it by getElementById in a similar loop.
Thanks!

Related

Getting Input Values from Appended Divs

I am having trouble getting the input values from a div that I appended. It returns as undefined. So basically I am creating the input element and giving it an Id. I have a function that when I clicked a button it is suppose to show the input value..
I am relatively new to JavaScript and I can't seem to find any solution for this. Please help me.. thank you
I am currently doing this in the same JavaScript script so there is no HTML script.
var question1ProjectTitleDiv = document.createElement("div");
var question1ProjectTitle= document.createElement("span")
var question1ProjectTitleName= document.createTextNode("Project Title:")
var question1ProjectTitleInput = document.createElement("input");
question1ProjectTitleInput.type= "text"
question1ProjectTitleInput.maxLength = 256;
question1ProjectTitleInput.id="question1ProjectTitleInputID"
question1ProjectTitleDiv.append(question1ProjectTitle)
question1ProjectTitle.append(question1ProjectTitleName)
question1ProjectTitleDiv.append(question1ProjectTitleInput)
questions.append(question1ProjectTitleDiv) //Add project title
console.log(question1ProjectTitleInput) // Returns <input type="text" maxlength="256" id="question1ProjectTitleInputID">
JS CODE:
let question1ProjectTitleInputID = $("#question1ProjectTitleInputID").val(); //Jquery
let question1ProjectTitleInputID2 = document.getElementById('question1ProjectTitleInputID') //Vanilla JS
You have the following statement:
question1ProjectTitleInput.id="question1ProjectTitleInputID"
So, if you use jquery to read the input, you should
let question1ProjectTitleInputID = $("#question1ProjectTitleInputID").val(); //Jquery

How do you return data from javascript into a html form?

I was wondering if anyone can help? What I am trying to do is retrieve the word count from javascript code into a form and then pass it into php along with the rest of the form which will check that the word count is a certain length or else it won't be submitted.
The javascript is as follows.
counter = function() {
var value = $('#msg').val();
if (value.length == 0) {
$('#wordCount').html(0);
$('#totalChars').html(0);
$('#charCount').html(0);
$('#charCountNoSpace').html(0);
return;
}
var regex = /\s+/gi;
var wordCount = value.trim().replace(regex, ' ').split(' ').length;
var totalChars = value.length;
var charCount = value.trim().length;
var charCountNoSpace = value.replace(regex, '').length;
$('#wordCount').html(wordCount);
$('#totalChars').html(totalChars);
$('#charCount').html(charCount);
$('#charCountNoSpace').html(charCountNoSpace);
};
$(document).ready(function() {
$('#count').click(counter);
$('#msg').change(counter);
$('#msg').keydown(counter);
$('#msg').keypress(counter);
$('#msg').keyup(counter);
$('#msg').blur(counter);
$('#msg').focus(counter);
});
My problem is returning wordCount into a hidden field in a form. I am not too good with javascript and am not sure how to modify this code to make it work. The rest I can figure out but am stuck here. Thank you for your help, it is greatly appreciated.
$('#wordCount').val(wordCount);
$('#totalChars').val(totalChars);
$('#charCount').val(charCount);
$('#charCountNoSpace').val(charCountNoSpace);
Use .val() instead of .html(), because .val() refers to the value of an input field.
Your HTML inside the form should include a hidden input field:
<input type="hidden" id="word_count" name="word_count" value="0" />
Then inside your JS:
$('#word_count').val(wordCount);
All together embedded inside your function:
counter = function() {
var value = $('#msg').val();
if (value.length == 0) {
$('#wordCount').html(0);
$('#totalChars').html(0);
$('#charCount').html(0);
$('#charCountNoSpace').html(0);
return;
}
var regex = /\s+/gi;
var wordCount = value.trim().replace(regex, ' ').split(' ').length;
var totalChars = value.length;
var charCount = value.trim().length;
var charCountNoSpace = value.replace(regex, '').length;
$('#wordCount').html(wordCount);
$('#word_count').val(wordCount);
$('#totalChars').html(totalChars);
$('#charCount').html(charCount);
$('#charCountNoSpace').html(charCountNoSpace);
};
$(document).ready(function() {
$('#count').click(counter);
$('#msg').change(counter);
$('#msg').keydown(counter);
$('#msg').keypress(counter);
$('#msg').keyup(counter);
$('#msg').blur(counter);
$('#msg').focus(counter);
});
If you have INPUT fields in your form, use val()
$('#wordCount').val(wordCount)
That would work for a field like this:
Be aware that there's a difference between "id" and "class". jQuery allows you to select elements based on their properties. The "id" property gets selected with "#", just like you'd do it in CSS. So make sure you have that "id='wordCount'" defined in your hidden field.
Have a look at this http://www.hscripts.com/scripts/JavaScript/word-count.php
There are plenty of examples online, just google "javascript count words in textbox"
Some imporntant notes:
A very long string with no spaces is still 1 word so don't forget to set the max length for fields
If you are doing this as a sort of validation be aware of the fact that you can not trust a form field because it can be easily manipulated, so don't forget to check the word count on the server side after the form is submitted.
The Code that you are showing is not just javascript it also includes jquery, please make sure you included jquery
<script src = "http://code.jquery.com/jquery-1.11.1.min.js"></script>
$('#field').val('asdf'); //Sets Value of a input type="text"
$('#field').html('sadf'); //Sets the html of a div
Using javascript you use either value for a input or innerHtml for a div or other text based element
document.getElementById('field').value = 'asdfsadf';
document.getElementById('field').innerHtml= 'asdfsadf';
Also instead of using a form submit consider using jquery $.ajax(there is nothing wrong with form submits but there are benefits to knowing jquery as well such as you came make async requests
http://api.jquery.com/jquery.ajax/
You will want to use a hidden field such as the following and have it in the form
<form id="myform" action='posttome.php'>
<input type="hidden" id="wordCount"/>
<input type="submit" value="sbumit"> //Submits Form
</form>
Then set its value by using of of three methods, a an elements html, an elements value, or a javascript variable $('#wordCount').val()
$('#wordCount').val($('#wordCountSoruceDiv').html()); // Sets the value to another divs html
$('#wordCount').val($('#wordCountSourceInput').val()); // Sets the value to another inputs value
$('#wordCount').val(wordCountVariable); // Sets the value to a variable

Populating form text inputs with data-* data using jQuery

I've been trying to wrap my head around this particular issue for two days now. I feel like I'm close, but I can't crack it. I have a div with data-* attributes:
<div class="pull-right" id="actions" data-ph-title="I am a title" data-ph-type="and a type" data-ph-source="from a source" data-ph-subject="with a subject">
When trying to alert - for instance - the value of "data-ph-title", I can do the following as apparently the dash between "ph" and "title" gets removed.
var info = $("#actions").data();
alert(info.phTitle);
That's great and it works (alerts: "I am a title"), but what I really want is to populate certain form fields with all of this data. I have named my form fields identical to the info object's properties, for example:
<textarea id="placeholder-title" name="phName"></textarea>
I'm trying to come up with a loop that will put all of the info object's property values into the corresponding text inputs (or textareas). This is where I'm getting stuck. I currently have the following code:
var info = $("#actions").data();
$.each(info, function(field, val){
$("[name='" + field + "']").val(val);
});
Any help would be greatly appreciated!
Your code works, so I don't really know what the problem is, aside from you not having a field named 'phName'.
This should be what you need. Iterate through the JSON object and populate the text areas:
var info = $("#actions").data();
for (var key in info) {
if (info.hasOwnProperty(key)) {
$("[name='" + key + "']").val(info[key]);
}
}
Here is a jsFiddle that demonstrates it working.
You don't seem to have a phName in #actions. But what about using an id on your form elements?
var info = $("#actions").data();
$.each(info, function(field, val){
$("#placeholder-" + field).val(val);
});
and
<textarea id="placeholder-phTitle"></textarea>
<textarea id="placeholder-phSource"></textarea>
...
Try this:
var fields = $('#myform input, #myform textarea');
for(var i=0; i < fields.length; i++){
var input = fields[i];
if(info[input.name]) input.value = info[input.name];
}

Dynamically loaded form won't update correctly

I have a form which is loaded into the page using .load(). I want to update the form with the HTML I compute in str, but my code isn't updating the form correctly. Why?
if($(this).is('.step3')){
//Splits the comma seperated values into input fields
var active_fields = ($('#templateFields').val()).split(',');
$('#loadedcontent').load('template.html #step3',function(){
$('#steps').text('Step Three');
$('#start.btn').text('Save Template & Values').removeClass('step3').addClass('step4');
});
str = "";
for(var i = 0; i<active_fields.length; i++){
str += '<label>'+active_fields[i]+'</label><input name="'+active_fields[i]+'" type="text" class="span3">';
}
$('form#values.well').html(str);
}
You have to put the form modification in the load completion function like this:
if($(this).is('.step3')){
//Splits the comma seperated values into input fields
var active_fields = ($('#templateFields').val()).split(',');
$('#loadedcontent').load('template.html #step3',function(){
$('#steps').text('Step Three');
$('#start.btn').text('Save Template & Values').removeClass('step3').addClass('step4');
str = "";
for(var i = 0; i<active_fields.length; i++){
str += '<label>'+active_fields[i]+'</label><input name="'+active_fields[i]+'" type="text" class="span3">';
}
$('form#values.well').html(str);
});
}
The way you were doing it, your code to modify the form was running before the form finished loading so it wouldn't find the content and thus couldn't modify it.
Sorry, I figured i couldnt nest a form within a form. I think thats why it didnt work

Javascript - filling textboxes with checkbox value

In my web application, I've set of checkboxes which on check populate a textbox above them.(If more than one checkbox is selected, then their values appear in the textbox separated by commas).
These set of checkboxes appear as rows in my HTML table.
Here's my HTML code.
<input type="text" id="newContactComment<%=rCount %>" name="newContactComment" size="45">
<input type="checkbox" id="commentText<%=rCount %>" name="commentText" value="<%=c.getComment_text() %>"
onclick="javascript:updateTextArea(<%=rCount%>);">
And the corresponding JS function is as follows:
function updateTextArea(rCount) {
var allVals = new Array();
$("#contactInfo input['commentText' + rCount]:checked").each(function() {
(allVals).push($(this).val());
});
$("#newContactComment" + rCount).val(allVals);
}
The rCount variable in the above function is the row # of my table.
Using this above, I'm not getting the expected behaviour..
For ex. If for row 1 of my table, I check chkbox 1 and 2, it correctly gets populated with values of those checkboxes. Now, for 2 of my table, I check only chkbox 3, it gets populated with the values 1,2 and 3 and not only 3 as I expect it to.
Any help will be greatly appreciated.
It would be better to use jQuery to set an event handler rather than setting it inline.
You want to use the onchange event not the onclick event.
If you add class names of checkboxes (or whatever you want) to the checkboxes the following will work:
$("input.checkboxes").change(function(){ //when checkbox is ticked or unticked
var par = $(this).closest("tr")[0];
var parID = par.id;
var patt1=/([0-9]+)$/g;
var rCount = parID.match(patt1); //Gets number off end of id
var allVals = new Array();
//Get all checkboxes in current row that are checked
$(par).find("td input.checkboxes:checked").each(function() {
allVals.push($(this).val());
});
$("#newContactComment" + rCount).val(allVals);
allVals = null; //empty array as not needed
});
I believe this or something along these lines will do what you want
You're trying to use the rCount variable from within the quoted string. Try this instead:
$("#contactInfo input['commentText" + rCount + "']:checked")

Categories

Resources