jQuery TypeError: $(...).val(...) is null - javascript

I cannot seem to locate the flaw in my code. I am using select2 for my select list and I have a button to the right that when clicked, performs the following script:
<script type="text/javascript">
function clearBiller() {
$('#bill_to').val('').trigger('change');
}
</script>
But when clicked, I receive the TypeError: $(...).val(...) is null error which references this script:
<script>
$(document).ready(function(){
$('#bill_to').on('change', function() {
if ($(this).val() == '')
{
$("#biller").show();
}
else
{
$("#biller").hide();
}
});
});
</script>
This issue is somewhere in this second function, I'm just not sure how to pin it down. At the moment this is the html in that part of the form:
<select id="bill_to" name="bill_to" class="js-example-basic-single form-control">
#if($shipment->bill_to)
<option value="{{$shipment->bill_to}}" selected>3</option>
#endif
#foreach($cCustomers as $customer)
<option value="{{$customer->id}}">{{$customer->customer_name}}</option>
#endforeach
</select>
<img src="/images/clear.png" height="15px" width="15px" style="margin-left: 5px;" onclick="clearBiller()">
<div id="existing_biller_details" class="hidden" name="existing_biller_details" style="margin-top:10px;">
</div>
Can anyone spot anything?
Update
Based on the suggestion below that worked the best in my case, my script now looks like this:
$(document).ready(function() {
if ($('.js-example-basic-single').val() == "") {
$('#biller').addClass('hidden');
$('#existing_biller_details').removeClass('hidden');
}
var $eventSelect = $("#bill_to");
$eventSelect.select2();
$eventSelect.on("select2:select", function (e) {
if ($eventSelect.select2().val() == '')
{
$('#biller').removeClass('hidden');
$('#existing_biller_details').addClass('hidden');
alert('cleared');
}
else
{
$('#biller').addClass('hidden');
$('#existing_biller_details').removeClass('hidden');
alert('not cleared');
}
});
});
The alerts above are only there to guide me in what isn't working. At the moment, I load up the page I have set the div with the id of "existing_biller_details" to already be hidden, but if a value is selected in the select2, the "hidden" class is removed.
My problem at the moment is that using the above code, only the "else" works completely. If I go through the initial "if" statement, it will only conduct $('#biller').removeClass('hidden') and then it can't go any further. I don't see any errors in the console but no alert comes up and the command $('#existing_biller_details').addClass('hidden') doesn't work either.

May be this help you
var $eventSelect = $("#bill_to");
$eventSelect.select2();
$eventSelect.on("select2:select", function (e) {
if ($eventSelect.select2().val() == '')
{
$("#biller").show();
}
else
{
$("#biller").hide();
}
});

You should trigger the change event directly on #bill_to
$('#bill_to').val('');
$('#bill_to').trigger('change');
But you should check Select2 docs as your main select gets hidden when Select2 is initialized and Select2 has its own set of events for change and such.

Related

.change() adds two values at the same time

Good day,
In my code, I need to use a drop-down list that has two values, say 1 and 2. When I click the #action-link link I append the corresponding text of the value into a textarea (#main-reply). I use Jquery .change() method to determine when selected value changed. Works ok unless I switch options several times and then it starts to add multiple values at a time even though I need insert in textarea only the corresponding value.
Here is a simple snippet of the code I use:
$("#action-link").click(function() {
if ($("#option").val() == 1) {
$("#main-reply").append("One");
}
});
$("#option").change(function() {
if ($(this).val() == 2) {
$("#action-link").click(function() {
$("#main-reply").append("Two");
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="option"><option value='1' selected>One</option><option value='2'>Two</option></select>
Add Value to textarea
<br>
<textarea id="main-reply"></textarea>
How can I solve this? Thanks!
Code adds another on-click listener when the value of the option was changed to '2' Link. Therefore the append() statament was being called multiple times, one from each listener.
$("#action-link").click(function() {
var option = $("#option").val();
if (option == 1) $("#main-reply").append("One");
else if(option == 2) $("#main-reply").append("Two");
});
Most of the times, this issue occurs when you load the same js file twice.
When JS file gets loaded twice, 2 on change events will get attached to the same event. Hence the actions will happen twice
Check your code and make sure that the JS file is not loaded twice
If it's not loaded twice and somehow this issue is still occurring, then use below code
$("#option").off().on("change",function() {
if ($(this).val() == 2) {
$("#action-link").click(function() {
$("#main-reply").append("Two");
});
}
});
This will remove any events attached to the change event and then adds the function
In your code click event is added on every change event for option value 2, which is not a good way as well.
You can write code as below
$("#action-link").click(function() {
if ($("#option").val() == 1) {
$("#main-reply").append("One");
} else if ($("#option").val() == 2) {
$("#main-reply").append("Two");
}
});
$("#option").change(function() {
// Just trigger click on change which handle other stuff
$("#action-link").trigger("click);
// You can write use below code as well.
// $("#action-link").click();
});
OR you can make it very simple as below which is dynamic regardless of any option value which will adds selected option value.
$("#action-link").click(function() {
appendOptionValue($("#option").val());
});
$("#option").change(function() {
appendOptionValue($("#option").val());
});
function appendOptionValue(optionValue){
$("#main-reply").append(optionValue);
}
this is it :
var val = $("#option").val();
$("#action-link").click(function() {
$("#main-reply").append(val);
});
$("#option").change(function() {
val = $(this).val();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="option">
<option value='One' selected>One</option>
<option value='Two'>Two</option>
</select>
Add Value to textarea
<br>
<textarea id="main-reply"></textarea>
this might helpful to you. Use text() instead of append
$(document).ready(function(){
$('#action-link').click(function(event) {
if($('#option').val()==1){
$('#main-reply').text('one');
}else{
$('#main-reply').text('two');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="option"><option value='1' selected>One</option><option value='2'>Two</option></select>
Add Value to textarea
<br>
<textarea id="main-reply"></textarea>

Checking value of an html select with jQuery

I have the following select box:
<select id="choose">
<option value=1>A</option>
<option value=2>B</option>
<option value=3>C</option>
</select>
<div id="hide-me">hide me!</div>
How can I hide an element when I select option "B"? I tried this:
<script type="text/javascript">
if ("#chose option:selected").val(2) {
$("#hide-me").hide();
};
</script>
I think I'm close, but nothing happens when I select option "B". Anyone have any suggestions?
You need to attach change event to select element to detect the option change. then use .toggle() with argument value not equal to 2 for making show/hide decision :
$('#choose').change(function(){
$("#hide-me").toggle($(this).val() != "2");
})
Working Demo
Listen to the change event of the #choose element, and add your conditional logic there.
Example Here
$('#choose').on('change', function () {
if (this.value === "2") {
$("#hide-me").hide();
} else {
$("#hide-me").show();
}
});
..equivalent, but perhaps less readable version:
Example Here
$('#choose').on('change', function () {
$("#hide-me").toggle(this.value !== "2");
});
As a side note, the value of the selected option is a string.
If you wanted to, you could also convert it to a number:
if (parseInt(this.value, 10) === 2) { ... }
or you could use == rather than ===: (not suggested, though. This could lead to logical errors.)
if (this.value == 2) { ... }
Without jQuery:
Example Here
document.querySelector('#choose').addEventListener('change', function () {
var element = document.getElementById('hide-me');
if (this.value === "2") {
element.style.display = 'none';
} else {
element.style.display = 'block';
}
});
The problem with your code is that:
It is not syntactilally correct — ("#chose option:selected").val(2) is an expression, which in turn should be wrapped in parentheses to be a proper condition for if, like this:
if (("#chose option:selected").val(2)) {
However, even after that your code is not correct because you're not actually using jQuery. You're calling method .val() just on a string "#chose option:selected", whereas that string should instead be a jQuery selector passed to jQuery itself:
if ($("#chose option:selected").val(2)) { // $ is the jQuery object that does all the work
However2, even that is incorrect, because you'd just be checking the value of an element right away. What you need is to wait for an element to be changed. Other answers explain very well how to do that.

Showing a conditional form field on load, and when preselected

I have the following jQuery code for showing/hiding a conditional form field (contained within tr#other-employer). This works fine, once the page is loaded and options are changed.
I would like make it so that the conditinal field shows when the page is loaded and the option selected in the drop-down list with #employer is pre-selected (this is done with PHP).
I have tried removing $('tr#other-employer').hide(); , but then this showed the conditional field on load regardless if the drop-down field is other or not.
A simple sample page is here: http://brenda.upreach.org.uk/beta/form.php
$(document).ready(function () {
$('tr#other-employer').hide();
$('#employer').change(function () {
if ($(this).val() == "Other") {
$('tr#other-employer').fadeIn();
} else {
$('tr#other-employer').hide();
}
});
});
Any help greatly appreciated!
You can add an if condition like below to check the status of the select box and do the needful.
$(document).ready(function () {
$('tr#other-employer').hide();
/*********************************/
if($("select#employer").val() == "Other")
{ $('tr#other-employer').fadeIn(); }
/*********************************/
$('#employer').change(function () {
if ($(this).val() == "Other") {
$('tr#other-employer').fadeIn();
} else {
$('tr#other-employer').hide();
}
});
});
you can also set the select box default option from jquery using
$("select#employer").val("Other");
I'm not sure I totally understand the question, but if you're looking for the same functionality this code provides, but without the action being a requirement, then just remove the .change() function, and swap out the this for the id:
$(document).ready(function () {
$('tr#other-employer').hide();
if ($('#employer').val() == "Other") {
$('#other-employer').fadeIn();
}
});
Edit:
The above should work, given the following HTML (I've removed the table code from both to simplify the explanation):
<form>
<select id="#employer">
<option value="Foo">Foo</option>
<option value="Other" selected="selected">Other</option>
</select>
<select id="#other-employer">
<option value="Foo">Bar</option>
</select>
</form>
Given the above code the #other-employer dropdown will display only if the 'Other' option is preselected on load.

Jquery: Hide a link button based on contains in option

EDIT: Will be more specific with requirements see bottom for additions:
I am trying to hide an a link (button formatted as a href), however I am trying to do it based on text found with in an option drop down menu.
So for example
<form id="phonetypeform">
<select name="porting-p1" class="dropdown">
<option value="">Please select an option...</option>
<option value="1">I want to keep my current phone number</option>
<option value="2">I want to choose a new number</option>
</select>
</form>
Next Step
If the 'please select an option' is selected it hides the a link, if anything else is selected then it shows the link
here is the jquery I have which is not working
$(document).ready(function() {
$("a.nextbutton").hide()
$('.dropdown').change(function() {
if($('.dropdown option:contains'Please)') {
$('a.nextbutton',this).hide();
} else {
$("a.nextbutton")show();
}
});
});
EDIT starts here:
thanks to everyone that has given me some answers, but what I now have works, but its not ideal, and ideally would like to use the contains, simple reason is I have about 20 of these scripts I would have to create and target the value, ugly!
to show my exact requirement please see the fiddle, while this is working, as I said I have many of these scripts to put in place, ideally I would like to:
1. target the text 'select...'
2. Have it so that it stays hidden until all options no longer contain 'Select...' (the contains should take care of that right)
Here is a fiddle to make life easier for anyone that can help?
http://jsfiddle.net/p3ewE/
END EDIT
Try this instead:
$("a.nextbutton").hide();
$('.dropdown').change(function () {
if ($('.dropdown').val() == "") {
$('a.nextbutton', this).hide();
} else {
$("a.nextbutton").show();
}
});
jsFiddle example
You had a few syntax issues with missing periods and brackets.
Typo here
if($('.dropdown option:contains(Please)')
^ ^
:contains()
Use this code
DEMO
$('.dropdown').change(function () {
if (this.value == "") {
$('a.nextbutton').hide();
} else {
$("a.nextbutton").show();
}
}).change();
Here is the link http://jsfiddle.net/XXDwr/5/
have a look at it.
$(document).ready(function() {
$(".nextbutton").hide();
$('.dropdown').on('change',function() {
var h= $('.dropdown').val();
if(h=="")
{
$(".nextbutton").hide();
}
else{
$(".nextbutton").show();
}
});
});
I hope you wanted to achieve this.
$(document).ready(function() {
var btnNext = $("a.nextbutton").hide();
$('.dropdown').change(function() {
if(this.value){
btnNext.show();
} else {
btnNext.hide();
}
});
});
You had a typo right before "please".
You could/should save the button in a variable so you don't have to make that query every time.

checkbox property using jquery

i m a beginner.
i want that when a checkbox is checked then it should allow user to write something in a txtbox. initially the txtbox is disabled. what i should write inside the function using jquery
<input type="checkbox" id="cb" />
<label for="cb">label for checkbox</label>
<input type="text" id="txt" disabled="disabled" />
<script type="text/javascript">
$(document).ready(function() {
var checkbox = $('#cb');
var textfield = $('#txt');
checkbox.click(function() {
if (checkbox.is(':checked')) {
textfield.removeAttr('disabled');
}
else {
textfield.attr('disabled', 'disabled');
}
});
});
</script>
working example with visibilty
working example with disabled-state
additionally:
as you are working with asp.net, your assignments should look like, eg:
var checkbox = $('#<%= this.cb.ClientID %>');
you should be aware of the way how the server-controls get rendered either (to choose an appropriate selector).
furthermore: you should also be aware of the fact, that disabled-inputs won't get posted, whereas readonly-inputs are no problem to handle...
$('#mycheckbox').click(function()
{
$("#mytextbox").attr('disabled','');
}
);
$(document).ready(function()
{
//To Disable the Check box on page Load
$('#TextBox').attr('disabled', 'disabled');
//On Click of the Check Box
$('#CheckBoz').click(function()
{
if($('#CheckBoz').is(':checked'))
{
$('#TextBox').removeAttr('disabled');
}
else
{
$('#TextBox').attr('disabled', 'disabled');
}
});
});
I Hope this code works perfectly for you and u jst need to paste it in your page and check the Component name according to it.

Categories

Resources