jquery not able to get value from a hidden field - javascript

I am trying to get a value from a hidden field. I am using the code
function foo(){
alert($('#idhere').val());
}
the answer i am getting is only the first word of that sentence.
the value is a large sentence I am using the above code inside a function foo and this function foo is called inside a append function inside a ajax call.
$.each(data, function(i, item) {
$("#news").append('<a onclick="foo()">xxx</a><input type="hidden" id="idhere" value="item[0]"');
}
Why am i getting only a single word as alert.
Am i doing it wrong

Well, where is "#idhere"?
There is no element that has this id assigned!

You have not given id idhere to element.
Try:
$("#news").append('<a onclick="foo()">xxx</a><input type="hidden" value="item[0]" id="idhere"');

i think you miss the id in hidden field
$("#news").append('<a onclick="foo()">xxx</a><input type="hidden" value="item[0]" id="idhere"');

Id should be unique! You use $.each, that means you probably will create many elements with the same id. That's bad.
$.each(data, function(i, item) {
$("#news").append('<a onclick="foo()">xxx</a><input type="hidden" id="idhere' + i + '" value="item[0]"');
}
Use:
function foo(){
alert($('#idhere0').val());
}
Or:
var vals = $.map($('input[type="hidden"]'), function(el) {
return $(el).val();
});
alert(vals.join('\n'));

Related

How Can I call a dynamic index in function cshtml?

I have this function :
<script>
function f(id){
return $("#" + id).val();
}
</script>
And this html's tag:
<input id=f(#payMethod) type="radio" value=" #method.Value" name="cartaCont" />
My id is buildered with a foreach that pass value to variable:
string payMethod = "payMethod";
payMethod += method.Text;
My question is: Is correct Call this index in an other function in this way ?? :
function() {
$('input[id ^= #PayMethod]').attr('checked', headerChecked);
}
thanks for feedback
It seems that you want to write some html and javascript code, relating to each item of a list.
In this case, I often prefer to directly write html and related javascript for event binding and code customization.
I supposing that method is your razor variable in your foreach, and methods is the enumerable variable to loop, you may would write this code for html
#foreach(var method in methods)
{
// this is C#, not javascript
// replacing spaces to build right id code for html
string payMethod = "payMethod" + method.Value.Replace(" ", "");
<text>
<input id="#payMethod" class="payMethodRadio" type="radio" value="#method.Value" name="cartaCont" />
<script>
$(document).ready(function () {
$("##payMethod").on('change', function (e) {
/* here if you want to write some javascript events for each item related to its html ID, for example change event */
});
});
</script>
</text>
}
But if you want to write some common jQuery code for this set of radio buttons, I' prefer to manage it with class selector rather than ID rules, as follow
function() {
$('payMethodRadio')...
}
Hope this, help you for better code management.
Br
Andryx
Try to add Onchange event to input.Here is a demo code:
#{var payMethod = 0;}
#foreach (var method in Model.Methods)
{
<input id="#payMethod" type="radio" value=" #method.Value" name="cartaCont" onchange="Add(#payMethod)"/>
payMethod++;
}
js:
function Add(id) {
$('#'+id).attr('checked', headerChecked);
}

Use of parent and find to select an item in the DOM

I have this js to update a span value with a new value coming from some math.
$('.ammesso').blur(function(){
ammesso = $(this).val();
perc_worst ='<?php echo $az_info['perc_worst']; ?>';
if(isNaN(ammesso)){
console.log(ammesso);
}else{
flusso = ammesso*perc_worst/100;
var jsonObject = $.parseJSON(prevs);
console.log(prevs);
$.each(jsonObject, function (i, obj) {
console.log(obj.id);
var id_item = obj.id;
//it gets the right value of 393
console.log('testo: '+$(this).parent('fieldset').find('.cl'+id_item).text());
});
console.log('flusso calcolato: '+flusso);
}
});
The html is the following:
<fieldset>
<label>Ammesso: </label><input type="text" name="ammesso[0]" value="" class="ammesso numerico">
<label>Incassi previsti: </label>
<ul id="lista">
<li class="soff_grp">Value - <span class="cl393">CASH</span></li>
</ul>
</fieldset>
console.log('testo: '+$(this).parent('fieldset').find('.cl'+id_item).text()); should return what is now inside the span but I miss what is wrong and why I cannot select the span.
My assumptions are:
with .parent('fieldset') I come back to the first DOM element input
and span have in common
with .find('.cl'+id_item) I get the first element with that class
(that is present in the rendered HTML)
What is wrong in how I use this two selectors? As per what I understand of what I have read in the jQuery documentation it seems to me the right way to select it!
the context of input element is lost in each function. this refers to element in jsonObject on which you are iterating. You need to store the element context outside each loop and then use it in each function:
var fieldset = $(this).parent('fieldset');
$.each(jsonObject, function (i, obj) {
console.log(obj.id);
var id_item = obj.id;
//it gets the right value of 393
console.log('testo: ' + fieldset.find('.cl'+id_item).text());
});

Modify the value of each textfield based on original value using jQuery

Is it possible to modify the value of each textfield present in a webpage, based on the original value, using jQuery or JavaScript?
For example, suppose I have 50 textfields in a page. I want to remove whitespace from the beginning and end of each textfield’s value. I don’t find it to be a good idea to call the function for every textfield individually. How can I do it without calling a function for each textfield?
Can just use val() with a callback argument. It will loop over all elements for you:
$('input[type=text]').val(function( index, originalValue){
return $.trim(originalValue);
});
val() API docs
You can execute this code:
$('input[type=text]').each(function (i, e) {
var $this = $(e);
$this.val($this.val().trim());
});
Get all the inputs from the page using jquery then run a loop, and for each element trim the value
<body>
<input type="text" value=" abc " >
<input type="text" value=" def " >
<input type="button" id="remove" value="Remove">
<script type="text/javascript">
$(document).ready(function(){
$('#remove').click(function(){
var inputs = $('input[type=text]');
$.each(inputs, function(index,input){
$(input).val($(input).val().trim())
});
});
});
</script>
</body>

How can I create dynamic controls and put their data into an object?

I created a div and a button. when the button clicked, there will be a group of element(included 1 select box and 2 text inputs) inserted into the div. User can add as many group as they can, when they finished type in data of all the group they added, he can hit save button, which will take the value from each group one by one into the JSON object array. But I am stuck in the part how to get the value from each group, so please help, thank you.
The code for the div and the add group button function -- AddExtra() are listed below:
<div id="roomextra">
</div>
function AddExtra() {
$('#roomextra').append('<div class=extra>' +
'<select id="isInset">' +
'<option value="Inset">Inset</option>' +
'<option value="Offset">OffSet</option>' +
'</select>' +
'Length(m): <input type="text" id="insetLength">' +
'Width(m): <input type="text" id="insetWidth">' +
'Height(m): <input type="text" id="insetHeight">' +
'</div>');
}
function GetInsetOffSetArray (callBack) {
var roomIFSDetail = [{
"IsInset": '' ,
"Length": '' ,
"Width": '' ,
"Height": ''
}];
//should get all the value from each group element and write into the array.
callBack(roomIFSDetail);
}
This should just about do it. However, if you're dynamically creating these groups, you'll need to use something other than id. You may want to add a class to them or a data-* attribute. I used a class, in this case. Add those classes to your controls so we know which is which.
var roomIFSDetail = [];
var obj;
// grab all of the divs (groups) and look for my controls in them
$(.extra).each(function(){
// create object out of select and inputs values
// the 'this' in the selector is the context. It basically says to use the object
// from the .each loop to search in.
obj = {
IsInset: $('.isInset', this).find(':selected').val() ,
Length: $('.insetLength', this).val() ,
Width: $('.insetWidth', this).val() ,
Height: $('.insetHeight', this).val()
};
// add object to array of objects
roomIFSDetail.push(obj);
});
you'd better not to use id attribute to identity the select and input, name attribute instead. for example
$('#roomextra').append('<div class=extra>' +
'<select name="isInset">' +
'<option value="Inset">Inset</option>' +
'<option value="Offset">OffSet</option>' +
'</select>' +
'Length(m): <input type="text" name="insetLength">' +
'Width(m): <input type="text" name="insetWidth">' +
'Height(m): <input type="text" name="insetHeight">' +
'</div>');
}
and then, usr foreach to iterate
$(".extra").each(function() {
var $this = $(this);
var isInset = $this.find("select[name='isInset']").val();
var insetLength = $this.find("input[name='insetLength']").val();
// ... and go on
});
A common problem. A couple things:
You can't use IDs in the section you're going to be repeating, because IDs in the DOM are supposed to be unique.
I prefer to use markup where I'm writing a lot of it, and modify it in code rather than generate it there.
http://jsfiddle.net/b9chris/PZ8sf/
HTML:
<div id=form>
... non-repeating elements go here...
<div id=roomextra>
<div class=extra>
<select name=isInset>
<option>Inset</option>
<option>OffSet</option>
</select>
Length(m): <input id=insetLength>
Width(m): <input id=insetWidth>
Height(m): <input id=insetHeight>
</div>
</div>
</div>
JS:
(function() {
// Get the template
var container = $('#roomextra');
var T = $('div.extra', container);
$('#addGroup').click(function() {
container.append(T.clone());
});
$('#submit').click(function() {
var d = {};
// Fill d with data from the rest of the form
d.groups = $.map($('div.extra', container), function(tag) {
var g = {};
$.each(['isInset', 'insetLength', 'insetWidth', 'insetHeight'], function(i, name) {
g[name] = $('[name=' + name + ']', tag).val();
});
return g;
});
// Inspect the data to ensure it's what you wanted
debugger;
});
})();
So the template that keeps repeating is written in plain old HTML rather than a bunch of JS strings appended to each other. Using name attributes instead of ids keeps with the way these elements typically work without violating any DOM constraints.
You might notice I didn't quote my attributes, took the value attributes out of the options, and took the type attributes out of the inputs, to keep the code a bit DRYer. HTML5 specs don't require quoting your attributes, the option tag's value is whatever the text is if you don't specify a value attribute explicitly, and input tags default to type=text if none is specified, all of which adds up to a quicker read and slimmer HTML.
Use $(".extra").each(function() {
//Pull info out of ctrls here
});
That will iterate through all of your extra divs and allow you to add all values to an array.

Cannot set innerHTML or $(this).val successfully in AJAX function

Using AJAX I have retrieved Json information but, during the function, I cannot display the text in the relevant Div.
The code works right to the bottom, as I can see using the console, but even if I put placeholder text in the div "place", the placeholder text stays the same right to the end of the function.
$.each(data, function(i,item){
if(i===0){
var placeHTML='<h2>'+item.name+'</h2>' +
'<p>where you can get <br>' +
'a pint of <em>'+item.pint+'</em> for only<br>' +
'<span>£'+item.cost+'!</span></p>';
window.localStorage.setItem("placeName", item.name);
window.localStorage.setItem("placeLoc1", item.location);
window.localStorage.setItem("placeLoc2", item.location2);
window.localStorage.setItem("placeEmail", item.email);
window.localStorage.setItem("placeNumber", item.number);
console.log("Data saved");
document.getElementById("place").innerHtml = placeHTML;
console.log("Data placed:");
console.log(placeHTML);
$("#loadText").fadeOut();
$('#place').fadeIn();
return false;
}
});
I have also tried replacing document.getElementById("place").innerHTML = foo to $("#place").val(foo) with no luck.
The div has the values id="place" and class="place".
document.getElementById("place").innerHtml = placeHTML;
should be
document.getElementById("place").innerHTML = placeHTML;
to do it with jQuery
$("#place").html(placeHTML)
val will set the value of something like an input field, to change the inner HTML with jQuery you want to use the html() function
Try this:
$("#place").html(foo)
Or
$("#place").text(foo)
Also, it is not innerHtml, it should be innerHTML here:
Change it to:
document.getElementById("place").innerHTML = placeHTML;
This line is wrong,
document.getElementById("place").innerHtml = placeHTML;
Change innerHtml to innerHTML (HTML should be caps),
document.getElementById("place").innerHTML = placeHTML;
May be try to use
$("#place").html(placeHTML);

Categories

Resources