setting attribute on select not persisting - javascript

I have a select input where I'm setting the multiple attribute via jQuery. I then have a console.log confirming that code functions correctly, then if i console.log again its no longer there. Any suggestions?
thisQuestionHTML is just a block of HTML code (2 divs wrapped around a select statement I'm casting as a jQuery object.
line 1: $(thisQuestionHTML).find('.answerValue').attr('multiple','multiple');
line 2: console.log($(thisQuestionHTML).find('.answerValue').attr('multiple','multiple'));
line 3: console.log($(thisQuestionHTML));
Line 1 : this is the non-debug code I'm expecting to actually set it
Line 2: this debug code is confirming its being set. It returns the select statement complete with the multiple="multiple"
<select class=​"answerValue" data-questionid=​"a0NJ0000008ZwjOMAS" multiple=​"multiple">​</select>​
Line 3: this debug code returns the select statement without the multiple attribute.
<div class=​"control-group">​
<span class=​"control-label">​MS picklist question​</span>​
<div class=​"controls">​
<select class=​"answerValue" data-questionid=​"a0NJ0000008ZwjOMAS">​</select>​
</div>​
</div>​

You're creating a new jQuery object on each of the three lines because thisQuestionHTML is just a HTML string. jQuery isn't updating the string, thisQuestionHTML is never changed.
Line 2: this debug code is confirming its being set.
This^ is not true, you are setting the value once again (note the two arguments to attr()).
Store a reference to the object instead of creating new each time:
var obj = $(thisQuestionHTML);
obj.find('.answerValue').attr('multiple','multiple');
console.log(obj); // contains updated select

use filter()
$(thisQuestionHTML).filter ('.controls .answerValue').attr('multiple','multiple');

Related

Javascript setInterval not working as expected [duplicate]

I had thought these two were the same, but they appear to not be. I've generally been using $obj.attr("value") to work with form fields, but on the page I'm currently building, $obj.attr("value") does not return the text I enter in my field. However, $obj.val() does.
On a different page I've built, both $obj.attr("value") and $obj.val() return the text entered in the form field.
What could account for $obj.attr("value") working as expected in one case but not in another?
What is the proper way to set and retrieve a form field's value using jQuery?
There is a big difference between an objects properties and an objects attributes
See this questions (and its answers) for some of the differences: .prop() vs .attr()
The gist is that .attr(...) is only getting the objects value at the start (when the html is created). val() is getting the object's property value which can change many times.
Since jQuery 1.6, attr() will return the original value of an attribute (the one in the markup itself). You need to use prop() to get the current value:
var currentValue = $obj.prop("value");
However, using val() is not always the same. For instance, the value of <select> elements is actually the value of their selected option. val() takes that into account, but prop() does not. For this reason, val() is preferred.
PS: This is not an answer but just a supplement to the above answers.
Just for the future reference, I have included a good example that might help us to clear our doubt:
Try the following. In this example I shall create a file selector which can be used to select a file and then I shall try to retrieve the name of the file that I selected:
The HTML code is below:
<html>
<body>
<form action="#" method="post">
<input id ="myfile" type="file"/>
</form>
<script type="text/javascript" src="jquery.js"> </script>
<script type="text/javascript" src="code.js"> </script>
</body>
</html>
The code.js file contains the following jQuery code. Try to use both
of the jQuery code snippets one by one and see the output.
jQuery code with attr('value'):
$('#myfile').change(function(){
alert($(this).attr('value'));
$('#mybutton').removeAttr('disabled');
});
jQuery code with val():
$('#myfile').change(function(){
alert($(this).val());
$('#mybutton').removeAttr('disabled');
});
Output:
The output of jQuery code with attr('value') will be 'undefined'.
The output of jQuery code with val() will the file name that you selected.
Explanation:
Now you may understand easily what the top answers wanted to convey. The output of jQuery code with attr('value') will be 'undefined' because initially there was no file selected so the value is undefined. It is better to use val() because it gets the current value.
In order to see why the undefined value is returned try this code in your HTML and you'll see that now the attr.('value') returns 'test' always, because the value is 'test' and previously it was undefined.
<input id ="myfile" type="file" value='test'/>
I hope it was useful to you.
Let's learn from an example.
Let there be a text input field with default value = "Enter your name"
var inp = $("input").attr("value");
var inp = $("input").val();
Both will return "Enter your name"
But suppose you change the default text to "Jose" in your browser.
var inp = $("input").attr("value");
will still give the default text i.e. "Enter your name".
var inp = $("input").val();
But .val() will return "Jose", i.e. the current value.
Hope it helps.
The proper way to set and get the value of a form field is using .val() method.
$('#field').val('test'); // Set
var value = $('#field').val(); // Get
With jQuery 1.6 there is a new method called .prop().
As of jQuery 1.6, the .attr() method returns undefined for attributes
that have not been set. In addition, .attr() should not be used on
plain objects, arrays, the window, or the document. To retrieve and
change DOM properties, use the .prop() method.
In order to get the value of any input field, you should always use $element.val() because jQuery handles to retrieve the correct value based on the browser of the element type.
jQuery('.changer').change(function () {
var addressdata = jQuery('option:selected', this).attr('address');
jQuery("#showadd").text(addressdata);
});
jQuery(".morepost").live("click", function() {
var loadID = jQuery(this).attr('id'); //get the id
alert(loadID);
});
you can also get the value of id using .attr()
this example may be useful:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
</head>
<body>
<input id="test" type="text" />
<button onclick="testF()" >click</button>
<script>
function testF(){
alert($('#test').attr('value'));
alert( $('#test').prop('value'));
alert($('#test').val());
}
</script>
</body>
</html>
in above example, everything works perfectly. but if you change the version of jquery to 1.9.1 or newer in script tag you will see "undefined" in the first alert.
attr('value') doesn't work with jquery version 1.9.1 or newer.
Example more... attr() is various, val() is just one! Prop is boolean are different.
//EXAMPLE 1 - RESULT
$('div').append($('input.idone').attr('value')).append('<br>');
$('div').append($('input[name=nametwo]').attr('family')).append('<br>');
$('div').append($('input#idtwo').attr('name')).append('<br>');
$('div').append($('input[name=nameone]').attr('value'));
$('div').append('<hr>'); //EXAMPLE 2
$('div').append($('input.idone').val()).append('<br>');
$('div').append('<hr>'); //EXAMPLE 3 - MODIFY VAL
$('div').append($('input.idone').val('idonenew')).append('<br>');
$('input.idone').attr('type','initial');
$('div').append('<hr>'); //EXAMPLE 3 - MODIFY VALUE
$('div').append($('input[name=nametwo]').attr('value', 'new-jquery-pro')).append('<br>');
$('input#idtwo').attr('type','initial');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="hidden" class="idone" name="nameone" value="one-test" family="family-number-one">
<input type="hidden" id="idtwo" name="nametwo" value="two-test" family="family-number-two">
<br>
<div></div>
jquery - Get the value in an input text box
<script type="text/javascript">
jQuery(document).ready(function(){
var classValues = jQuery(".cart tr").find("td.product-name").text();
classValues = classValues.replace(/[_\W]+/g, " ")
jQuery('input[name=your-p-name]').val(classValues);
//alert(classValues);
});
</script>
If you get the same value for both property and attribute, but still sees it different on the HTML try this to get the HTML one:
$('#inputID').context.defaultValue;
In attr('value') you're specifically saying you're looking for the value of an attribute named vaule. It is preferable to use val() as this is jQuery's out of the box feature for extracting the value out of form elements.
I have always used .val() and to be honest I didnt even know you could get the value using .attr("value"). I set the value of a form field using .val() as well ex. $('#myfield').val('New Value');

getElementsByName not working

Looked up several "Answers" to this problem, but it was mostly just people not treating the result returned by getElementsByName() as a NodeList!
Edit: I am trying to hide/show elements based on an element being clicked. I could hardcode this using document.getElementById and just add one everytime I have an element I want to hide/display. But it would be ideal if I could retrieve all elements named something and just run a loop on them to hide/show. Then I could just tag an element with a name when writing and this loop would work without alteration. Below my code is simply trying to popup an alert with the value for testing purposes. As for now, it consistently breaks with a null error. I am using and designing for internet explorer 9 as this is what the company uses.
Code:
<input type="radio" name="Area" value="Engineering" id="EngineeringCheck" onclick="javascript: ShowContentEngineering();" />Engineering
<script type="text/javascript">
function ShowContentEngineering() {
alert(document.getElementsByName('EngineeringAreas')[0].value)
document.getElementById('InformationBlock').style.display = 'block';
}
</script>
<h5 name="EngineeringAreas" value="luls"> WHAT THE HECK </h5>
Code above breaks saying that the object at getElementsByName('EngineeringAreas')[0] is null. Clearly, right below it, it is not null... Am I confusing getElementsByName('string')[0].value with the value of the element? Or is it retrieving some other value?
Ideally, I'd add other elements later, tag them with "EngineeringAreas" and never have to mess with the hide/show function.
Edit: Here is the error message:
Unhandled exception at line 53, column 9 in http://localhost:57264/Home/Index
0x800a138f - Microsoft JScript runtime error: Unable to get value of the property 'value': object is null or undefined
Here you go... seems:
onclick="javascript: <--- not necessary - just reference the function name
ShowContentEngineering needs to be set in the window context
You're referencing the "value" attribute of an element that doesn't allow value attributes (h5)
I made it work instead grabbing the innerHTML of the h5
Code
<input type="radio" name="Area" value="Engineering" id="EngineeringCheck" onclick="ShowContentEngineering();" />Engineering
<h5 name="EngineeringAreas"> WHAT THE HECK </h5>
<script>
window.ShowContentEngineering = function() {
alert(document.getElementsByName('EngineeringAreas')[0].innerHTML)
document.getElementById('InformationBlock').style.display = 'block';
}
</script>
Here's a working fiddle: https://jsfiddle.net/mu970a8k/
Insert .attributes[1] between .getElementsByName('EngineeringAreas') and .value. The 1 points to the second attribute in the <h5> element named EngineeringAreas, which is value. Placing .value after .attributes[1] should return the value text “luls” in the alert box. The alert code should then be set up like this:
alert(document.getElementsByName('EngineeringAreas')[0].attributes[1].value);
More Info: http://www.w3schools.com/jsref/prop_attr_value.asp

Add code examples on your page with Javascript

I have a html code inside string
string_eng += '<b>Year Bonus</b> - bonus for each year</br></br>';
And I want to put this inside textarea, but when I do it, the result is:
- bonus for each year
It simply deletes all things inside the html tags. I just want to show all the code inside the string. I already tried <xmp>,<pre>, but none of them worked.
Thanks for any help.
EDIT.
Code with which I input data from the array to the textarea/code.
$('body').append('<code class="code_text"></code>');
for(var i=0; i<tag_list.length; i++){
var string='';
string+='---------------------------------------------------------------------------------\n';
string+='tag: '+tag_list[i][0]+'\n';
string+='nazwa_pl '+tag_list[i][1]+'\n';
string+='nazwa_eng '+tag_list[i][2]+'\n';
string+='tekst_pl '+tag_list[i][3]+'\n';
string+='tekst_eng '+tag_list[i][4]+'\n';
string+='\n\n\n';
$('.code_text').append(string);
}
I tried this using jsfiddle:
HTML
<textarea id="code"></textarea>
JavaScript
$(document).ready(function() {
var string_eng = '';
string_eng += '<b>Year Bonus</b> - bonus for each year</br></br>';
$("#code").html(string_eng);
});
Output (contained in textarea)
<b>Year Bonus</b> - bonus for each year</br></br>
Try it here: http://jsfiddle.net/UH53y/
It does not omit values held within tags, however if you were expecting the <b></b> tags to render as bold within the textarea, or the <br /> tags to render as line breaks, this wont happen either. textarea does not support formatting.
See this question for more information: HTML : How to retain formatting in textarea?
It's because you're using the jQuery .append method which seems to parse the string and insert it afterwards. I don't know jQuery at all, so there might be another special jQuery method, but here is a simple fix:
$('.code_text').append(document.createTextNode(string));
Edit:
I just read and tried the answer of Salman A. The "special jQuery method" exists and he used it. You can use this:
$('.code_text').text(string);

jQuery - cannot extract .data() attribute with calculated key

I'm working with this jQuery code:
$('#selection').bind("change", function(){
var selected = $(this).find('option:selected');
var datavar = selected.text().toLowerCase();
//alert(datavar);
//alert('looking for '+datavar+$('#test').data(datavar));
//alert($('#test').data('var1'))
});
http://jsfiddle.net/Zwe6h/
The purpose is to choose what data variable you wish to extract from the #test element by using the #selection element. it should alert you as to what the value of that data variable is.
The datavar variable is set correctly as alert(datavar); prints out the correct value.
However, the second test alert (which is the purpose of this test) displays it as undefined. The third test alert simply tests to make sure you can explicitly call the data variables by hard-coding the variable.
I am not understanding why it is coming back with undefined. I tested the type of datavar, and it is indeed a string, so I would expect it to behave just as it would if it were hardcoded. Can someone shed some light on this?
Try this:
alert('looking for '+datavar + $('#test').data($.trim(datavar)));
Issue is with some newline chars (casued by html formatting) in the text selected as they are not included between the option start and end tag. So you just need to trim it.
Fiddle
Or fix your options to include the text in between closing and ending tags.
<select name='selection' id='selection'>
<option value='1'>var1</option>
<option value='2'>var2</option>
</select>
Fiddle2

Problem with dropdown and codeigniter

i'm using 2 dropdowns where the second gets populated from the first choice.
My problem is that i'm not getting the value from the first dropdown.
What i get is [object Object].
Here's the javascript and php code:
Thanks.
Javascript:
function getState(){
$("#selectestate").bind("change",function(){
$("#selectcity").load("results/ajaxcity", {stat: $(this).val()} ); //This is where the problem is
alert({stat: $(this).val()});//Shows [object Object]
});
return false;
}
PHP:
$curstat=$this -> input -> post('state'); //current selected state in first dropdown
<tr>
<?php $js = 'id="selectstate" onChange="getState();"';?>
<td><h3> State: </h3></td>
<td id="selectestate"><?php echo form_dropdown('state', $stat, $curstat, $js);?></td>
</tr>
<tr>
<td><h3> City: </h3></td>
<td id="selectcity"><?php echo form_dropdown('city', $cit);?></td>
</tr>
You need to alter this code:
$("#selectestate").bind("change",function(){
to this:
$("#selectestate select").bind("change",function(){
You are asking for the value of the <td id="selectstate"> ... which is of course null. #selectstate select loads the actual <select> element that you are looking for, which will then enable you to get its value.
You will also want to change $("#selectcity") to $("#selectcity select") to avoid the same problem in your anonymous function.
Finally, your alert is behaving as expected. {} defines an object in Javascript. So you are alerting an object containing a single attribute. Just alert($(this).val());// Should show the value
If it still fails it's because either:
A) Your URL is wrong
or
B) There is something wrong with the php function called by results/ajaxcity
EDIT:
Smacks head: I should have caught this. In your code you have this function:
1. function getState(){
2. $("#selectestate select").bind("change",function(){
3.
4. $("#selectcity select").load("results/ajaxcity", {stat: $(this).val()} );
5. alert($(this).val());
6. });
7. return false;
8. }
Your generated HTML looks something like this:
<select name="state" id="selectstate" onChange="getState();">
THE PROBLEM: When you use the <select> for the first time your function is called and jQuery binds an anonymous function to the change event for select (line #2) that will be executed every time the change event fires from this select from now on. Every time you select the dropdown a new anonymous function is bound by line #2 and all of the functions that are currently bound to the dropdown are executed. (So if you use the dropdown N times the "change" function will fire N-1 times.)
THE SOLUTION: Use $(document).ready() to bind your function. Your restructured code will look like this:
<script type="text/javascript">
function getState(element){
$("#selectcity select").load("results/ajaxcity", {stat: $(element).val()} );
alert($(element).val());
return false;
}
</script>
//... snip ...
<?php $js = 'id="selectstate"';?>
//... snip ...
<script type="text/javascript">
$(document).ready(function() {
$("#selectestate select").bind("change", getState);
});
</script>
There is no value for td element, which you are accessing in "#selectestate" selector. Instead of {stat: $(this).val()} you should find inner select element {stat: $(this).find("select").val()}
You're loading the .val() of a <td> element ($(this), inside your handler for a TD). You need to get the id of the <select> tag.
If you really can't find the ID (or codeigniter doesn't set it.. impossible to tell from your example since form_dropdown() is creating it), then instead of $(this).val() you could try $('select',this).val() which will find the value of the first <select> tag within the TD.
Also in your debugging, {stat: $(this).val()} is an object, so of course that's what alert() shows you. Try using firebug, and then change alert() to console.log() -- the firebug console will show you the full object. You could also simply do alert($(this).val()) -- though realize of course that it will be wrong due to the first paragraph above.

Categories

Resources