Why i always fail to make check mark to checkbox via javascript? - javascript

Look to my code below :
HTML :
<input type="checkbox" name="xyz[1][]" id="sel_44" style="margin:2px;" value="12345" onclick="myClick(this)">
Javascript :
<script>
$('#sel_44').attr("checked", true);
</script>
I already try every method (method that suggest by acceptance answer) in this URL : Check/Uncheck checkbox with javascript?
My Problem and Question :
I can sure $('#sel_loc_cb_44') is not null
and not undefined. But i can make checkmark via javascript or jquery.
How to fix my code and what's the source of problem?
Please kindly add jsfiddle to your solution post. thank you

try using
$('#sel_44').prop("checked", true);
you must change the propery of the DOM object instead of attribute

try this with jquery:
$("#sel_44").prop('checked',true);

Since jquery 1.6+ prop method provides a way to explicitly retrieve property values, while attr retrieves attributes. Here checked is a property. So use prop for checking a checkbox.
$('#sel_44').prop("checked", true);

Try this
$(document).ready(function() {
$('#sel_44').attr("checked", true);
});
I have tried in the jsfiddler, looks like you need to put your code inside the document ready function.
https://jsfiddle.net/o2gxgz9r/5935/

$(function(){
$('#sel_44').prop('checked',true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="xyz[1][]" id="sel_44" style="margin:2px;" value="12345">

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');

Why can't I change my disabled checkbox to enable?

Simple question, so I made sure to try and a lot of solutions before posting this. I have a checkbox and I can't seem to enable it.
With vanilla JS, I've tried removing the attribute, as well as setting the disabled flag to false, and also using jQuery i've tried to use the Prop to no success.
'''html
<input type="checkbox" id="chkAllowToAdminService" name="chkAllowToAdminService" disabled="disabled" data-init-plugin="switchery">
'''
I've tried the following and none of them are working (vanilla JS and jQuery)
'''
document.getElementById('chkAllowToAdminService').disabled = false;
document.getElementById('chkAllowToAdminService').removeAttribute('disabled);
$('#chkAllowToAdminService').prop("disabled", false);
'''
No error messages at all, just nothing seems to be happening.
To remove attribute you may use removeAttribute(name). In your case:
const checkbox = document.querySelector('#chkAllowToAdminService')
checkbox.removeAttribute('disabled')
To set attribute setAttribute(name, value).
// In jQuery
$('#chkAllowToAdminService').attr('disabled','disabled'); // Add disabled
$('#chkAllowToAdminService').removeAttr('disabled',''); // Remove disabled
// OR
$("#chkAllowToAdminService").attr("disabled",true);
$("#chkAllowToAdminService").attr("disabled",false);
// In JavaScript
document.getElementById("chkAllowToAdminService").disabled = true;
document.getElementById("chkAllowToAdminService").disabled = false;
I think you might have two issue :
make sure you have unique id of element 'chkAllowToAdminService' no other element have same id.
in your remove attribute syntex : document.getElementById('chkAllowToAdminService').removeAttribute('disabled);
I can see quote ' is missing at last.

Change attribute

I've got a selection/dropdown with ID #pa_buy-sell[]. What I want to do is if the value is "buy" I want to change the attribute data-required="yes" to data-required="no" from a input field with class wpuf__regular_price_657. I also want to hide the span with class required. The code has to work in WordPress.
I'm quite new in this, so I'm not sure what's the right code. But I thought something like this could be a good starting point:
$('#pa_buy-sell[]').change(function(){
if($(this).val() == 'buy'){
//something need to happen here
}
});
Can someone help me with this?
Your code is correct until now. You have to replace the comment with the following lines:
$('.wpuf__regular_price_657').data('required','no');
$('span.required').hide();
To change the attribute to yes or no. you can use this:
$(".wpuf__regular_price_657").attr("data-required","no");
or you can use disabled as true or false, if you dont want to take input as
$(".wpuf__regular_price_657").attr("disabled", true);
and for hiding the particular span:
$("span.required").hide();
This will work fine in wordpress too
Hope it helped you
Please check with "===" which confirms Strong type checking (type and value) comparison and also refer the code for hiding the div with class required.
<script>
var $ = jQuery.noConflict();
$('.pa_buy-sell.wpuf_pa_buy-sell_657').change(function(){
if($(this).val() === "buy"){
$(".wpuf__regular_price_657").attr("data-required","no");
$("span.required").hide();
}
});
</script>

Javascript to select checkbox

What would be the javascript below to select the checkbox for value 0?
<input name="bootproto" id="bootproto" type="radio" value="0" key="bootproto">
I tried using
$('input[name="bootproto"]').click() but it didnt seem to work.
$("#bootproto").prop("checked",true);
Since you're using jquery, just set the property "checked" to true (I don't see why you're name selecting when you have a perfectly good ID there as well)
If you want to check it ONLY if value=0, add an if statement before this.
document.getElementById('bootproto').checked = true;
OR
$('#bootproto').prop('checked',true);
I figured out that $('input[value="0"]').click() seemed to work for me.
Try this,
$('input[name="bootproto"]').attr('checked',true);
Checked is actually an attribute of the input tag of type radio, So that you can use the .attr() function to set its checked attribute as true.
DEMO
You don't mention that you're using jQuery even tho you've apparently tried the syntax. On the off-chance you're not using it, try:
var i = document.querySelector('input[value="0"]').checked = true;
I would do the following : $('input[name="bootproto"]:not(:checked)').

jquery not getting hidden field data

Im sending over some json data and assigning to a hidden field using:
#Html.Hidden("hidden-places", #Model.Places)
inside my javascript i am doing the following to retrieve the data:
var places = $('#hidden-places').val();
however it just comes back as undefined.
i am using this for google maps...
i tried something like:
$(document).ready(function () {
places = $('#hidden-places').val();
// Onload handler to fire off the app.
google.maps.event.addDomListener(window, 'load', initialize);
});
but no luck.
You need to use an ID selector:
places = $('#hidden-places').val();
Note that #.
With this:
$('hidden-places').val();
...you're looking for the value of a <hidden-places> element. Probably not what you mean. You likely want the value of a field with the ID hidden-places:
$('#hidden-places').val();
I had multiple elements with the same id on the page causing the problem
"hidden-places" will be the ID of the field and what your jQuery is looking for is going to be an HTML element called hidden-places.
You should use
$('#hidden-places').val()
did you check if you set a prefix in your viewdata?
how is the element in DOM? checked the value and id?
maybe your element is like
<input id="prefix_hidden-places" name="prefix.hidden-places" type="hidden" value="10" />

Categories

Resources