Populating form text inputs with data-* data using jQuery - javascript

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

Related

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

Get all form values into javascript array

I am attempting to get all the form values into a normal array[]. I had it working for tags but then I added some tags and can't seem to get it.
With just tags it worked with this
var content = document.querySelectorAll("#form input[name='content[]']");
I am currently trying something like this
var content = document.elements["content[]"].value;
This form can change from user input down the road as each section of the form is a module that they choose to add. It is also important to get the values in order, if that isn't possible then I would need to make it a JSON array. Pure javascript or jquery is fine either way.
Thank you for any help.
EDIT
I used this to solve my problem
var contents=[]
var content = $('#form').serializeArray()
for (var i = 0; i < content.length; i++) {
contents[contents.length]=content[i].value
};
Try
html
<form id="form">
<input type="text" name="content[]" value="abc" />
<textarea name="textarea" value="">123</textarea>
</form>
js
$(function() {
var form = $("#form");
// escape `[]`
var content = form.find("input[name=content\\[\\]]");
// array `literal declaration`
var _arr = [content.prop("value")];
// map all form values to single array
var arr = $.map(form.serializeArray(), function(v, k) {
return [v.value]
});
// array literal with `textarea` `value`
var t = [$("textarea").prop("value")];
console.log(_arr, arr, t);
// _arr: `["abc"]` , arr:`["abc", "123"]` t:`["123"]`
})
Demo.
See Arrays

Grails richui autocomplete passing object to function or updating object ID

I've got a table with a load of auto complete boxes in it which look like so...
<richui:autoComplete style="width:500px" name="objSelect[${newRow-1}].id" value= "" action="${createLinkTo('dir': 'object/searchAJAX')}" forceSelection = "true" maxResultsDisplayed="20" minQueryLength ="3" onItemSelect="updateHiddenInput(id,${newRow-1})" />
I've got it to call a function called updateHiddenInput when a user selects a value passing in the id selected as well as the row the autocomplete is on (this function then updates a hidden field in the same row, using the values passed in, with the ID). The function looks like so: -
function updateHiddenInput(id, num){
var objID = "objectID[" + num + "].id";
$(document.getElementById(objID)).val(id);
}
Everything works until I add a new row within my table, this pushes everything down one row and stops the autocomplete from updating the right rows hidden field (as its still referencing the old row).
Currently I have another piece of code that goes through and renames all the fields when a new row is inserted, but I have no idea how to update the autocomplete so that it passes through the right row number, anyone know how I can alter this?
The only other alternative I could think of would be to just pass through the object itself as well as the ID I can then locate the hidden based off the object, but I can't work out how to do this, any suggestions gratefully received! :S
I've tried changing
onItemSelect="updateHiddenInput(id,${newRow-1})"
to
onItemSelect="updateHiddenInput(id,this)"
Theoretically so I can just pass through the autocomplete object and from there just traverse the page to find the hidden field I want to update. However when I then attempt to use that object in my function, for example with something like: -
var mynumber = $(myobject).closest('td').find('input').val();
I always get an "undefined" returned when I try to alert back the value...
If I just put in an alert(myobject) in the function it returns AutoComplete instance0 autoLook[0].id but if I've inserted new lines the id value doesn't change (i.e the objects id is now autoLook[3].id but it still shows [0], which I think could be part of the problem but I've got now idea how I can update this value...
I notice when looking in firebug at the html there is a /script linked to the autocomplete which could be the problem as this doesn't get updated when new lines are added and I can see multiple references to the old/original id value (see below) so maybe the passing through of this isn't passing the current objects values through...?
<script type="text/javascript">
var autoCompleteDataSource = new YAHOO.util.XHRDataSource("/Framework/object/searchAJAX");
autoCompleteDataSource.responseType = YAHOO.util.XHRDataSource.TYPE_XML;
autoCompleteDataSource.responseSchema = {
resultNode : "result",
fields : [
{ key: "name" },
{ key: "id" }
]
};
;
autoComplete = new YAHOO.widget.AutoComplete('autoLook[0].id','ad186a42e45d14d5cde8281514f877e42', autoCompleteDataSource);
autoComplete.queryDelay = 0;
autoComplete.prehighlightClassName = 'yui-ac-prehighlight';
autoComplete.useShadow = false;
autoComplete.minQueryLength = 3;
autoComplete.typeAhead = false;
autoComplete.forceSelection = true;
autoComplete.maxResultsDisplayed = 20;
autoComplete.shadow = false;
var itemSelectHandler = function(sType, args) {
var autoCompleteInstance = args[0];
var selectedItem = args[1];
var data = args[2];
var id = data[1];
updateHiddenInput(id,this) };
autoComplete.itemSelectEvent.subscribe(itemSelectHandler);
</script>
My thanks so far to user1690588 for all his help thus far! :)
On further digging I'm convinced that my issues is down to the line autoComplete = new YAHOO.widget.AutoComplete('autoLook[0].id','a5b57b386a2d1c283068b796834050186', autoCompleteDataSource); specifically the part where its inputting autoLook[].id and if I could change this I'd then be ok, but this line is auto generated and I've got no idea how to update it, anyone have any similar experience?
I have not much idea about your gsp page but I tried it on my side:
My gsp:
<!DOCTYPE html>
<html>
<head>
<resource:autoComplete skin="default"/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
var counter = ${list.size()};
function asd() {
jQuery.ajax({
url: " ${createLink(controller: 'oauthCallBack', action: 'testAuto')}",
data: "idx=" + counter++,
success: function (data) {
jQuery("#tableId").append("<tr><td>" + data + "</td></tr>");
}
});
}
function updateHiddenInput(id, tg) {
jQuery(tg).val(id);
}
</script>
</head>
<body>
<g:form>
<table id="tableId">
<g:each in="${list}" var="vr" status="idx">
<tr>
<td>
<richui:autoComplete name="name" id="uniqueId${idx}" action="${createLinkTo('dir': 'oauthCallBack/test')}" onItemSelect="updateHiddenInput(id, someId${idx})"/>
<g:hiddenField name="someName" id="someId${idx}" value=""/>
</td>
</tr>
</g:each>
</table>
</g:form>
<button onclick="asd()">Add</button>
</body>
</html>
My action:
def testAuto() {
render template: 'addNew', model: [idx: params.idx]
}
My template(addNew):
<richui:autoComplete name="name" id="uniqueId${idx}" action="${createLinkTo('dir': 'oauthCallBack/test')}"
onItemSelect="updateHiddenInput(id, someId${idx})"/>
<g:hiddenField name="someName" id="someId${idx}" value=""/>
Try this..,.
EDIT.....................................................................................
I supposed that you have successfully updated all the input field names. Then you can edit hidden field like:
View:
<tr class="dummyClass">
<td>
<richui:autoComplete name="name[${idx}]" id="uniqueId[${idx}]" action="${createLinkTo('dir': 'oauthCallBack/test')}" onItemSelect="updateHiddenInput(id, this)"/>
<g:hiddenField name="someName[${idx}]" id="someId[${idx}]" value=""/>
</td>
</tr>
jQuery:
function updateHiddenInput(id, tg) {
jQuery(tg._elTextbox).closest("tr.dummyClass").find("input[type=hidden]").val(id);
}
EDIT.....................................................................................
Why you need to change the 'id'? Changing name is sufficient to send values in order. And you can update the hidden field without id as above edit.
If you still need to change the id then you can change it by cloning the tr and then use regex. See this answer for full working example.

Javascript unable to extract value of text field in Table

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!

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

Categories

Resources