I have three radio buttons and I want, by default, to have the "BOTH" location which has a value of 3 to be clicked on page load so that it will run my jQuery post function. The radio button is filled-in giving the appearance of being clicked, but the click is not happening to post my function. Once I change the radio button however, the code works fine.
This is my code:
$("input:radio[name='location'][value='3']").click();
$('input[name="location"]').change(function() {
var location = $('input[name="location"]:checked').val(); var category = getUrlVars()["category"];
$.post(
'db/functions/package_conf.php',
{category:category, location:location},
function(data) {
$('#package_info').html(data);
});
});
Would you try to register the event handle first before trigger the event? $("input:radio[name='location'][value='3']").click(); after the .change' event..
you may consider use the checked too, like $("input:radio[name='location'][value='3']").prop("checked", true).
but for my personally preference, any default state should be done before hand and not the in the script, for example initiate your radio DOM element to have checked property <input type="radio" value="3" checked />, and then onLoad script call the post directly (anyway POST is not designed for this purpose, just imagine POST as to save something, if you just want to get/query some data, GET would be more reasonable)
click was triggered before the change's event handler was regestered.
$('input[name="location"]').change(function() {
var location = $('input[name="location"]:checked').val(); var category = getUrlVars()["category"];
$.post(
'db/functions/package_conf.php',
{category:category, location:location},
function(data) {
$('#package_info').html(data);
});
});
$("input:radio[name='location'][value='3']").click();
$(window).on('load', (e) => { $("#test").focus() })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="test" value="23" type="number" style="font-size:30px;width:150px;">
Related
I have an script in which I'm going to add a file XLS, once that I validate the file format, I close a bootstrap's modal and open another modal which is an confirmation window to see whether the user is sure to upload that file.
This confirmation window has a confirmation button, once clicked I want that execute me an function which it's going to run an AJAX to make the request to the server.
However, because of that, I had the following doubts:
Which of the 2 ways is better (and the most correct) to run the code and why?
Why is the click event of the first input file executed if there has not been an event change? I mean, I add a file and the event change is executed and I can make clicks many times as I want, is not it supposed that I must add another file so that I can run the function inside again?
Put an event inside an event, has it a name?
$(document).ready(function(){
//First input file
$(document).on('change','#file', function(){
let file = $(this);
let nameFile = file[0].files[0].name;
let button = '<button type="button">Clic input 1</button>';
$('#button').html(button);
$('#button').click(function(){
console.log('CLICK IN FIRST INPUT FILE!');
});
});
//Second input file
$(document).on('change','#file2', function(){
let file = $(this);
let nameFile = file[0].files[0].name;
let button = '<button type="button">Clic input 2</button>';
$('#button2').html(button);
});
$('#button2').click(function(){
console.log('CLICK IN SECOND INPUT FILE!');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="file" name="file" />
<div id="button"></div>
<div style="margin-top:20px"></div>
<input type="file" id="file2" name="file2"/>
<div id="button2"></div>
Put an event inside an event, has it a name?
It has, the name is Bad Idea. Let me Expain. What happens when you execute the following code.
$('#button').click(function(){
console.log('CLICK IN FIRST INPUT FILE!');
});
A click event is registered to the button. Once an event is registered, it will fire everytime no matter how many times you click.
When you put that code inside another event handler like the first example, it gets executed everytime the file-input changes and a new event handler is registered. So when you select a file, and then decide to change it, file-input changes twice and you get 2 click events registered. Now click on the button, you get 2 new console log printed by one click!!! Try it..
Why is the click event of the first input file executed if there has
not been an event change
Because that's how event handler works, you register once, they get fired everytime after that.
Which of the 2 ways is better (and the most correct) to run the code
and why?
Obviously not the first one, because it is a bad idea, Not the second one either. In case of second one you are attaching event to a division that will contain the button. So you don't need to click on the button, just click anywhere right side of the button, the event gets fired!!!
So if none of them is right, what can we do?
Do not generate button/any html element by javascript for such simple tasks. Do it with HTML, plain and simple.
Do not nest event handler into another i.e put one event handler inside another, it will complicate things. Just put all event handlers directly inside document.ready event of jQuery. document.ready only fires once.
When you need to control user action then show/hide your button or other html element by javascript based on required conditions.
My suggestion is doing something like this.
$(document).ready(function(){
// Hide the button at first
$('#button').hide();
// When File-input changes
$('#file').change(function(){
if(**the file-input has a file selected**){
$('#button').show();
}
else{
$('#button').hide();
}
});
// When Button Clicked
$('#button').click(function(){
// Do the action
});
});
Which of the 2 ways is better (and the most correct) to run the code and why?
I believe this is better:
//Second input file
$(document).on('change','#file2', function(){
let file = $(this);
let nameFile = file[0].files[0].name;
let button = '<button type="button">Clic input 2</button>';
$('#button2').html(button);
});
$('#button2').click(function(){
console.log('CLICK IN SECOND INPUT FILE!');
});
Mainly because it's more readable and easy to follow. There is no need to have the button click event set up AFTER the input has been changed. It is better to change the STATE of the button, as you are doing. Even better would be to hide/show the button like:
$('#button2').show();
And have it initially hidden with:
<div id="button2" style="display: none">Click me</div>
Why is the click event of the first input file executed if there has not been an event change?
In my test, this all worked correctly.
How is called this?
The change events should only be called when you click and assign a file to the input.
you are binding the same event multiple times to the same button object. binding the same event to the same object in another event that may reoccur will result in binding it over and over (stacks events and fire them and in this case "it" multiple times). binding an action to an event should happen only one time per object. and I see that you are binding the click event to the div instead of the button. maybe you need to consider dynamic binding using .on() like this
$(document).ready(function(){
//first file change event
$(document).on('change','#file', function(){
let file = $(this);
//handling empty selection
if(file[0].files.length == 0){
$('#button').html("");
return;
}
let nameFile = file[0].files[0].name;
let button = '<button type="button">Clic input 1</button>';
$('#button').html(button);
});
//second file change event
$(document).on('change','#file2', function(){
let file = $(this);
//handling empty selection
if(file[0].files.length == 0){
$('#button2').html("");
return;
}
let nameFile = file[0].files[0].name;
let button = '<button type="button">Clic input 2</button>';
$('#button2').html(button);
});
//first button dynamic event (doesn't stack)
$('#button').on('click','button', function(){
console.log('CLICK IN FIRST INPUT FILE!');
});
//second button dynamic event (doesn't stack)
$('#button2').on('click','button', function(){
console.log('CLICK IN SECOND INPUT FILE!');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="file" name="file" />
<div id="button"></div>
<div style="margin-top:20px"></div>
<input type="file" id="file2" name="file2"/>
<div id="button2"></div>
note that you need to handle not choosing a file (e.g. files count is 0) like in my code
Put an event inside an event, has it a name?
It does have a name. It's called "daisy chaining" and it's not a good idea.
not enough rep to comment
I've had cause to do this. I had the unpleasant task of mucking through 2 years of code written by one person with little maintenance or code discipline. I wanted to keep the code structure intact, so I daisy-chained click events to perform some enhancements.
To avoid some problems mentioned in the better answers above, simply remember to call $(selector).off("click") before binding the next event.
const mainevent = (e)=>{
e.preventDefault();
your event data
.then((e) => {
second event()
})
.catch((error) =>
alert(error.message))
};
}
I am using the following javascript to hide a form if the user clicks on a checkbox.
I am trying to get the code to run on page load but am not able to work out how to do this. Can anyone help?
$('#no_cage').change(function(){
if (this.checked) {
$('#cage_details').fadeOut();
} else {
$('#cage_details').fadeIn();
}
});
HTML:
<input name="no_cage" id="no_cage" type="checkbox" value="1" <?php echo $checked; ?>><label for="no_cage">Check if not required</label>
<div id="cage_details">
<form>
...
</form>
</div>
This works fine when a user clicks on the checkbox. But does not when it pulls from the DB and the checkbox is already selected on page load.
Just add this code inside the document ready handler. It will trigger the change event handler without it needing to actually change...
$('#no_cage').trigger("change");
Alternatively, just trigger the event where you declare it...
$('#no_cage').change(function(){
if (this.checked) {
$('#cage_details').fadeOut();
}
else {
$('#cage_details').fadeIn();
}
}).trigger("change");
That will add the event handler and then immediately execute it, in order to set the form to the correct state when the document has loaded.
You can either change the checked property or trigger the change event.
$(function() {
$('#no_cage').change(function() {
if (this.checked) {
$('#cage_details').fadeOut();
} else {
$('#cage_details').fadeIn();
}
});
// Change the checked property
$('#no_cage').prop('checked', true);
// OR trigger the change event
// $('#no_cage').trigger('change');
});
I have a series of dynamically generated inputs with the same class, eg:
<input class="addressitem" type="text"/>
<input class="addressitem" type="text"/>
<input class="addressitem" type="text"/>
After the user inputs data into each field I want to take that data and place it in the value field of a hidden input.
However, I am having trouble figuring out the best way to do this. So far I've tried:
$(".addressitem").focusout(function() {
var addressinput = $(this).val();
console.log(addressinput);
});
and
$(".addressitem").change(function() {
var addressinput = $(this).val();
console.log(addressinput);
});
But I cannot get anything to appear in console.
Could anyone point me in the right direction?
Both of your approaches should work as long as you define them inside the document.ready event and you do not have any other script errors in your page.
$(function(){
$(".addressitem").change(function() {
var addressinput = $(this).val();
console.log(addressinput);
});
$(".addressitem").focusout(function() {
var addressinput = $(this).val();
console.log(addressinput);
});
});
You may use your browser console to verify the existence of other script errors in the page.
Also remember that, change event occurs on the text input fields when the focus is out. So you will see the console.log when user changes the focus from the textboxes. If you want instant updates, you should consider using keyUp event
Here is a working sample.
EDIT : As per the comment : I had the fields generated by a Jquery click function. I had to move my code within the click function for it to work.
No you don't need to. You can simply use the jQuery on delegation method. When you register an event handler with jQuery on, It will work for current and future elements(dynamically injected) in the DOM.
So your code will be
$(function(){
$(document).on("change",".addressitem",function() {
var addressinput = $(this).val();
console.log(addressinput);
});
});
This might be the best option, as you said they are dynamically generated inputs.
$(document).on("blur",".addressitem",function() {
var addressinput = $(this).val();
console.log(addressinput);
});
WORKING FIDDLE
Check your console
On focusout in HTML5 as following:
<input type="text" onfocusout="makeITUpperCase(this)">
And in javascript as following:
function makeITUpperCase(e) {
console.log(e.value);
e.value = e.value.toUpperCase();
}
The function takes 'this' object as e which can be used to get value or alter
I am using CSS toggle button to show active or inactive. It uses a HTML checkbox and modifies its CSS to look like toggle slide bar. I have bound the onClick event on the checkbox so that when the checkbox is checked it sends id via an AJAX request to a URL that updates the status of the row with the given id to active and echoes active. The PHP echo returned by URL is now displayed below the toggle button.
Here, when checkbox is clicked first the checkbox is checked and the AJAX request is sent to the URL, what I want is when the checkbox is clicked the checkbox doesn't get checked or unchecked but the AJAX request is sent and when response arrives then only change status of checkbox to checked or unchecked as per the response. How can I achieve this? Can someone clarify with an example?
The ajax handler code is:
function toggleStatus(id)
{
$.ajax
({
url: "project/news/toggleStatus?id="+id,
type: 'get',
success: function(result)
{
$('#status_txt'+id).html(result);
$('#status_txt'+id).attr('class', 'status_'+result);
},
error: function()
{
$('#modalinfo div').html(' <div class="modal-content"><div class="modal-header"><h2>Could not complete the request.</h2></div></div>');
$('#modalinfo').modal('show');
}
});
}
The html is:
<td class="numeric"><label class="switch">
#if($data->status=="active")
<input class="switch-input" type="checkbox" onClick="javascript:toggleStatus({{$data->id}})" checked="checked"/>
#else
<input class="switch-input" type="checkbox" onClick="javascript:toggleStatus({{$data->id}})"/>
#endif
<span class="switch-label" data-on="On" data-off="Off"></span>
<span class="switch-handle"></span>
</label>
<span id="status_txt{{$data->id}}" class="status_{{$data->status}}">#if($data->status=="inactive")<p style="color:red;">{{ ucfirst($data->status) }}</p>#else{{ ucfirst($data->status) }}#endif</p></span>
</td>
use java script:
suppose checkbox id="ck"
<input type="checkbox" id="ck" onClick="if(ck==1)unChecked();else doChecked();">
ck=0; //init checkbox is unchecked
function doChecked(){
document.getElementById("ck").checked="checked";
document.getElementById("ck").checked=true;
ck=1;
}
function unChecked(){
document.getElementById("ck").checked="";
document.getElementById("ck").checked=false;
ck=0;
}
Firstly I would suggest removing the onclick attribute from your checkboxes HTML; they're outdated, ugly and bad for separation of concerns. You're using jQuery for your AJAX, so you may as well use it to hook up your events too.
Secondly, You can prevent the default behaviour of the checkbox to stop the check appearing when the element is clicked. You can then set the checked property manually in the success callback of the AJAX request, something like this:
<input type="checkbox" name="foo" id="foo" value="foo" />
$(function() {
$('#foo').change(function(e) {
e.preventDefault();
var checkbox = this;
var id = checkbox.id;
$.ajax({
url: "project/news/toggleStatus?id="+id,
type: 'get',
success: function(result) {
checkbox.checked = true;
$('#status_txt' + id).html(result).attr('class', 'status_' + result);
},
error: function() {
$('#modalinfo div').html('<div class="modal-content"><div class="modal-header"><h2>Could not complete the request.</h2></div></div>');
$('#modalinfo').modal('show');
}
});
});
});
It is worth nothing though is that this behaviour is non-standard. By that I mean that the user will click the checkbox and it will appear that nothing has happened until the request completes. This may confuse your user in to clicking the checkbox again, and causing repeated AJAX requests. I would suggest you add a loading indicator to the page when the checkbox is clicked so that it's obvious that work is being done based on the users' actions.
Also, I would strongly suggest you use DOM traversal to find the related #status_txtXXXX elements from the clicked checkbox instead of ugly concatenated ids - it's better semantically and means the JS is less coupled to the UI.
I am using Jquery and Ajax for performing the action, I need after loading complete page, a code click on the every button automatically.
I used the following javascript code for click all the buttons in the end of my page. but it is not working.
<script type='text/javascript'>
document.getElementByClassName('sub').click();
</script>
Structure of my Page code
[JQuery]
[PHP]
[HTML]
[Javascript]
I set all the buttons type as "BUTTON", When I set
type="submit"
The Autoclick code only work on the first button, but with the "button" type it is not working with any of them.
If I click manually on that buttons they are working properly.
Please give any suggestion. Thank You.
Youre using the wrong function. Elements is plural in that method.
document.getElementsByClassName('sub');
Additionally, calling click on this NodeList will not work. You need to loop through and call the event on each index.
Also, you say you're using jQuery. To ensure your call happens after DOM ready, wrap your JS with $().ready().
Last, use the tools you've provided yourself, in this case jQuery, and select your element that way.
$(document).ready(function(){
$(".sub").click()
});
In jQuery you can trigger the click like
$( ".sub" ).trigger( "click" );
Because you retrieve a NodeList(as pointed out in the comments) :
$(document).ready(function () {
var butEl = document.getElementsByClassName('sub'),
count = butEl.length;
for (i = 0; i < count; i++){
butEl[i].click();
}
});
Also is getElementsByClassName
If you're trying to click on multiple different form submit buttons, it makes sense that the browser will POST for only one of them - one page can't simultaneously navigate to multiple different URLs.
Similarly, when you change type to button, none of the forms will be submitted, even though you're clicking on the buttons.
If you know what you're doing, you could always add submit event handlers to all of your forms, and submit them via ajax requests instead - which should allow multiple of them to be processed. Note you may need to work out some extra logic for displaying success/failure for each form to the user since the browser won't navigate you to any of the existing "submitted" pages.
$(document).on('submit', 'form', function() {
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
dataType: 'json',
data: $(this).serialize(),
success: function(data) {
// Add logic here for handling success for each form, if required
},
error: function(xhr, err) {
// Add logic here for handling errors for each form, if required
}
});
return false; // To stop the browser processing this form
});
With this method, your first attempt with type="submit" buttons should work - however I would encourage you to be as specific as possible with your element selectors for both the forms and the buttons you're trying to target.