I have table with the following id inside one of the rows
<td class="firstRow"> <span id="randomWordToTranslate"></span></td>
the firstRow class just include padding preferences in css.
In my java script class, I am calling two functions
the first randomly assigned a value to this id , so when I am loading my page I will get a different word each time : this part is working
$("#randomWordToTranslate").html(current_dict[listOfKeys[Math.floor(Math.random() * listOfKeys.length)]]);
the second inside a button listener trying to get the value of the word inside this field whenever the button is clicked
var spanishWord = $("#randomWordToTranslate");
var inputValue = $(spanishWord).val();
but when I doing console.log(inputValue) I am printing an empty row into my log.
Any ideas?
thanks
Since the <span> isn't an <input> tag (or other form input like <select>), it will not have a .val() (value). Instead, you need either .html() or .text():
var spanishWord = $("#randomWordToTranslate");
var inputValue = spanishWord.text();
// Or:
var inputValue = spanishWord.html();
Related
I have a form where the user can dynamically add or remove sets of fields. For each set of fields, when the user enters/changes a value in the upc[] text input I want to make an Ajax query and populate the corresponding desc[] text input. I can capture the change event, but have not been able to read or modify the dynamically create desc[] field:
This snippet does not have the Ajax call as for now I just want to know I can set desc[x].val(). I have tried to associate the dynamic field with a parent element that existed when the DOM was created...but still no luck.
$(document).on('change', '.upcScan', function(){
var upcIdx = $(this).index('.upcScan');
var upcVal = $(this).val();
alert ("The current index is "+upcIdx+" and the value is "+upcVal);
var descName = "desc["+upcIdx+"]";
var descVal = $("#addClient input[name='"+descName+"']").val();
alert("desc field is "+descName+" and value is "+descVal);
});
The code above returns null. If I try to set the val nothing happens.
What am I missing?
I have a form in which a user can click a button and add additional fields as needed. Later on, user clicks submit, i do some error checking via ajax. if the additional fields are blank, i want to highlight them in red to let user know its required data.
jquery to add row:
$('#addPerson').click(function(){
var row = "<div id='row_"+rowNum+"'><div class='leftBigRow'><input type='text' class='field' id='addPerson[name][]' name='addPerson[name][]' placeholder='persons name'></div>";
$('.additionalPeople').append(row);
rowNum++;
my ajax call returns a string of field ids that have errors. for example result could be:
//firstname,lastName,zipCode,...etc
so my errorcheck is:
if(result.length > 0)
{
var errors = result.split(",");
for (i=1;i<errors.length;i++)
{
alert(errors[i]);
$('#'+errors[i]).addClass('error');
alert($('#'+errors[i]).val());
}
$("#subForm").attr("disabled", "disabled");
}
the first alert returns what i would expect "addPerson[name][0]";
the second alert returns undefined. telling me it cant find that field....
i have added a fiddle:fiddle
in my fiddle var result is a representation of what i get back from the ajax call. my ultimate goal is to get each field added by pressing yes to turn red if blank....
You don't have an element with id equal to "addPerson[name][0]". When adding new input elements to DOM, you have to include rowNum in their id and name attributes.
Do not include "[" and "]" in name/id attributes. Use:
var row = "<div id='row_"+rowNum+"'><div class='leftBigRow'><input type='text' class='field' id='addPerson_name_"+rowNum+"' name='addPerson_name_"+rowNum+"' placeholder='persons name'></div>";
When you declare your dynamic element's id, you cannot use an array there. You can concatenate it with the rowNum count that you already have.
I have updated your JSFiddle here: http://jsfiddle.net/Myra4/3/
(Observe how I changed the dynamic element's id and your simulated 'result' variable)
I did it in JSFiddle for you so you can immediately verify that it works.
Use .on to bind later created DOM elements.
http://api.jquery.com/on/
Been looking around and I cant seem to find an answer to this so maybe im wording it wrong but here it goes.
So I have a table displaying data from a database. In jQuery I have made it so a row can be added with empty inputs and then submitted to the database, this works fine.
I am now attempting to be able to edit it. So each row will have a button to edit that row, the button will put the row values into inputs so you can change the value and update the database. How can I do this? I was looking into using this here but Im not sure how I can get the value of the input boxes without them having some sort of ID.
jQuery I was trying to use:
$('#tbl').on('click','.xx',function() {
$(this).siblings().each(
function(){
if ($(this).find('input').length){
$(this).text($(this).find('input').val());
}
else {
var t = $(this).text();
$(this).text('').append($('<input />',{'value' : t}).val(t));
}
});
});
Am I over thinking this? Should I just be grabbing the values and then putting them in pre-made input boxes?
Update:
HTML:
sb.AppendLine("<table style='width: 80%;'>")
sb.AppendLine("<tr class='inputRowbelow'>")
sb.AppendLine("<td style='width: 20%;' class='ui-widget-header ui-corner-all'>Area</td>")
sb.AppendLine("<td class='ui-widget-header ui-corner-all'>Details</td>")
sb.AppendLine("<td class='ui-widget-header ui-corner-all'>Options</td>")
sb.AppendLine("</tr>")
For Each w In workItems
sb.AppendLine("<tr>")
sb.AppendLine("<td>" & w.area & "</td>")
sb.AppendLine("<td>" & w.details & "</td>")
sb.AppendLine("<td><a href='#' class='fg-button ui-state-default ui-corner-all edit'><img src='/images/spacer.gif' class='ui-icon ui-icon-pencil' /></a></td>")
sb.AppendLine("</tr>")
Next
sb.AppendLine("</table>")
There are a couple of ways to do this, including changing your VB code to add extra data to the html, but I will answer this from a pure javascript/JQuery solution.
First of all you need to handle the click event for each edit button, after that you find the matching row, and then you can get the first to td elements of that row...
$(".edit").click(function(e){
e.preventDefault();//prevent the link from navigating the page
var button = $(this);//get the button element
var row = button.closest("tr");//get the row that the button belongs to
var cellArea = row.find("td:eq(0)");//get the first cell (area)
var cellDetails = row.find("td:eq(1)");//get the second cell (details)
//now you can change these to your inputs and process who you want
//something like this...
ConvertToInput(cellArea, "area");
ConvertToInput(cellDetails, "details");
});
function ConvertToInput(element, newId){
var input = $("<input/>");//create a new input element
input.attr("id", newId);//set an id so we can find it
var val = element.html();//get the current value of the cell
input.val(val);//set the input value to match the existing cell
element.html(input);//change the cell content to the new input element
}
Here is a working example
From that you can then do the saving that you say you have already implemented, using the ID values of each field to get the values to save.
Instead of using a For Each ... in ... Next loop, use a a For loop with a counter. give each button and each row an ID with the current counter value at the end. You can then use Jquery to make each row editable separately, because each row has a row number now.
I am trying to pass the value selected from a drop down box placed inside a div to a php script which then inserts it into the database.
I was told that to access input element from a div use .
("#divname").text();
I fiddled around and found out that this is just the string of all options which is basically just all the text inside the div.
Could anyone help me to select just the value which is selected? Thanks in advance
Try this way:
("#divid").find('selectSeclector').val();
You need to select the select element from inside the div and use .val() to get the selected value. If you know the id of the select element then just do $('#selectId').val();. ("#divname").text(); will only give all the inner text values of all the elements inside the div including itself.
Assuming you have following dropdown box
<select id = "drop"><option value = "hello">Hello</option></select>
Below code will return you selected value
$("#drop").change(function(){
var value = $(this).val();
});
You can simply get the selected value of the dropdown using its element ID
var drpdwnid = document.getElementById("dropdownlistid");
var selectedvalue = drpdwnid.options[drpdwnid.selectedIndex].value;
Why doesn't this work?. Here the input type is text:
var name = $("input[name='Event[name]']").serializeArray();
name = name[0].value;
var description = $("input[name='Event[description]']").serializeArray();
description = description[0].value;
When I want to get the from a textarea instead, it doesn't work.
This should work:
var name = $("input[name='Event[name]']").val();
var description = $("input[name='Event[description]']").val();
Let jQuery handle value.
The .val() method is primarily used to get the values of form elements such as input, select and textarea.
Replace your code as .val() to .text()
value isn't a property of a textarea. Textarea's are nodes that have content. Use the JQuery attribute for textContent.
A textarea as no value attribute. Use $("input[name='Event[description]']").val() since jQuery folds all values for all kind of input elements (input, select, checkbox and textarea) into this function call.
That means you should always use .val() to get the value for anything - your code will be more simple and you can even change the type of an input element without breaking anything.
Is there any particular reason as to why you use get value as array?
If not see below :
var name = $('#name').val();
var description = $('textarea#description').val();
considering name and description is what you have given as id for text field and text area.