multiple submit buttons only first initializes javascript - javascript

I'm echoing the Submit Button as seen below in each row of a Table. When clicked the Submit Button the Javascript initializes and alert()'s the response. The issue is only the first Button works as intended and subsequent buttons redirect to foobar.php.
Submit Button:
<form name="savefilenote" id="savefilenote" method="post" action="forbidden-savefilenote.php?notetype=2">Note: <input id="filenote" name="filenote" type="text" value="'.$filenote.'"> <input id="filename" name="filename" type="hidden" value="'.$filename.'"> <input type="submit" value="Save"></form>
Javascript:
<script>
$(function(){
$('.savefilenote').on('submit', function(e){
// prevent native form submission here
e.preventDefault();
// now do whatever you want here
$.ajax({
type: $(this).attr('method'), // <-- get method of form
url: $(this).attr('action'), // <-- get action of form
data: $(this).serialize(), // <-- serialize
beforeSend: function(){
$('#result').html('');
},
success: function(data){
$('#result').html(data);
if(data === "0") {
alert("foo");
}
if(data === "1") {
alert("bar");
}
}
});
});
});
</script>

Use a class instead of an id.
$("#savefilenote") can find only one instance of a button since and ID works for a specific element. If you change it to $(".savefilenote") and apply the same class to all buttons it should work.

id should be specific to a single element. Using the same id to identify multiple tags, you'll end up only affecting the first element in the body. If you want to associate a behavior to a group of elements, you'll need to use a class.

Related

How to apply more than one JavaScript onchange for multiple image upload input fields

I have a page where users can upload up to 5 images to their post. For clarity for the user I have made it so that there are 5 empty boxes with separate input fields like this:
<span id="enableFileUpload_1" class="upload-image-svg-wrapper">
<input id="imageUploadID_1" type="file" accept="image/*"/>
</span>
<span id="enableFileUpload_2" class="upload-image-svg-wrapper">
<input id="imageUploadID_2" type="file" accept="image/*"/>
</span>
To handle these I have some JavaScript which looks for onchange event on the first field:
jQuery(function($) {
var imageNumber = 1;
$('body').on('change', '#imageUploadID_'+imageNumber, function() {
$this = $(this);
file_data = $(this).prop('files')[0];
form_data = new FormData();
form_data.append('file', file_data);
form_data.append('action', 'file_upload');
form_data.append('security', blog.security);
$.ajax({
url: blog.ajaxurl,
type: 'POST',
contentType: false,
processData: false,
data: form_data,
success: function (response) {
alert("ok");
}
});
});
});
This works fine for the first image but it seems like imageNumber is always 1 so the onchange event only fires for the first image/input and does nothing for the rest.
Questions
Do I have to write 5 different $('body').on('change', '#imageUploadID_1', function() for each input field and then have them call the same function?
Is there a smarter way of doing this?
You can use jQuery to assign the same onClick handler to every span with a class of upload-image-svg-wrapper. You've already written the code within the handler to work on any image that is clicked because you've used this to get the form data.
$('span.upload-image-svg-wrapper > input').on('change', function() {
Above, instead of selecting the entire body of the document we instruct jQuery to select all spans with the class upload-image-svg-wrapper that are inputs. And then we remove the selector from the on change handler.

Bootstrap radio buttons "Yes" or "No" not picking up change or click event

I have a set of radio buttons which are loaded in via AJAX once a user has been selected. They have the option to have their access set to Yes or No depending if it is required or not. When the button is clicked the active class is applied and when i get the value of the checked item it returns the expected value.
The problem i am having is that the change event and the click event, neither of them will fire when the button is clicked?
HTML:
<div class="col-md-4">
<div class="btn-group" data-toggle="buttons" style="width:100%">
<label class="btn btn-default <?php if($access['has_access']){?> active <?php } ?>" style="width:50%">
<input type="radio" name="<?=$access['id']?>" id="option1" value="1" <?php if($access['has_access']){?> checked <?php } ?>>Yes
</label>
<label class="btn btn-default <?php if(!$access['has_access']){?> active <?php } ?>" style="width:50%">
<input type="radio" name="<?=$access['id']?>" id="option2" value="0" <?php if(!$access['has_access']){?> checked <?php } ?>>No
</label>
</div>
</div>
JS:
$(document).on('click', 'input[type="radio"]', function(){
var data = {};
data.access_id = $(this).attr('name');
data.value = $(this).val();
data.user_id = $('input[name="user_id"]').val();
$.ajax({
url: '/ajax/change_access.php',
type: 'POST',
cache: false,
data: data,
dataType: 'JSON',
headers: {"cache-action":"no-cache"}
}).done(function(data){
console.log('here');
}).fail(function(data){
console.log("error");
});
});
I have tried changing the target to just input but this has no affect on radio buttons but is triggered by text inputs. Could be missing something obvious but unable to see it, any help would be much appreciated.
NOTE: This is technically wrong/unnecessary, per comments below. Although it would still attach events. It's just not the best way to attach events.
(Incorrect statement; original post) The above code will ONLY attach events on initial document load. NOT when the DOM is mutated (when you insert these elements via AJAX). This will fix your issue:
$(document).on('DOMNodeInserted', function(e) {
//You can use $(this) instead of $(e.target) if you'd like.
if($(e.target).attr("type") === "radio") {
$(e.target).click(function() {
var data = {};
data.access_id = $(this).attr('name');
data.value = $(this).val();
data.user_id = $('input[name="user_id"]').val();
$.ajax({
url: '/ajax/change_access.php',
type: 'POST',
cache: false,
data: data,
dataType: 'JSON',
headers: {"cache-action":"no-cache"}
}).done(function(data){
console.log('here');
}).fail(function(data){
console.log("error");
});
});
}
});
This will be triggered every single time a new element is attached to the DOM. And I added a check to make sure the added element is a radio button. If so, then attach the click to it.

Trigger click once when page is loaded

I have a form in my page like so:
<form id="shipping" action="some-action-url" method="post">
<ul>
<li>
<input id="ship238280" name="method" value="238280|479435" type="radio" checked="checked">
<label for="ship238280">Transport (€0,00)</label>
</li>
<li>
<input id="ship292259" name="method" value="292259|580109" type="radio">
<label for="ship292259">Pick up (€0,00)</label>
</li>
</ul>
</form>
I'm using a SaaS platform so I have limited access to scripts and need to make use of what's actually available. So I'm looking for more of a workaround....
In above form I have checked the first option. To actually set the first shipping option I have to submit the form. Then in the system this option is set.
So I have a function that submits the form:
function sendform(){
var loader = $('.cart-loader');
var form = $('#shipping');
$(loader).show()
$.ajax({
type: "POST",
url: $(form).attr('action'),
data: $(form).serialize(),
success: function(data) {
$(loader).hide()
//$(this).unbind()
}
});
}
And a click event for when I click one of the options:
$('#shipping input').on('click', function(){
sendform()
});
What I want now is to submit the form on page load. So I have created something like this:
$(function(){
$('#shipping input').each(function(){
if($(this).is(':checked')){
$(this).trigger('click') // or sendform()
}
});
});
What happens now is that the form keeps submitting because everytime the page reloads (after submit) it wants to submit again!
How can I work around this knowing that it needs to submit first to set the option?
I tried things like $(document).one('ready', function(){ or something like $(this).unbind() in ajax success function.
I'm a bit lost :) So any help greatly appreciated!!
Try something like this: https://jsfiddle.net/noidee/uvm6jw3b/
$(document).ready(function(){
if( localStorage.getItem('submited') !== '1' ){
$('#myform').submit();
localStorage.setItem('submited', '1');
}
});

Add a dynamic form field after pressing a button

I have a form with a simple button $builder->add('language_switcher', ButtonType::class); which should simply, if pressed, add another field. To do that, I used Symfony's cookbook http://symfony.com/doc/current/form/dynamic_form_modification.html
$builder
->get('language_switcher')
->addEventListener(
FormEvents::POST_SUBMIT,
function () use ($builder, $options) {
$preparedOptions = $this->prepareOptions($options['data']['productCustomizations']);
$builder->add('lang_switcher'), ChoiceType::class, $preparedOptions);
}
);
When now submitting it via AJAX
<script>
var $button = $('#xyz');
$button.click(function() {
var $form = $(this).closest('form');
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
success: function(html) {
console.log(html);
$('#xyz').replaceWith($(html).find('#lang_switcher'));
}
});
});
</script>
I'm getting the error Buttons do not support event listeners. So I tried it out with a hidden field. I added the hidden field to the Form, set the EventListener to it, and added this data to my AJAX request
data[$('#id_of_hidden_field').attr('name')] = 1;
However this did nothing. The example in the cockbook is after submitting a choice field so I don't know how to adapt it to my needs. I couldn't use a SubmitType, because then it would submit the form, right? I just want to have it with a simple button.
The problem is, that, when I do a console.log(html) I don't see the new html element, so it seems like I'm not getting to the EventListener which is weird, because if I dump contents inside the listener I'm getting some data. It just seems like I'm not getting it inside the response
Ok, got it. The problem was that I used the builder inside the POST_SUBMIT event but I had to use a FormInterface. Since I couldn't add it AFTER submit I had to buy the same callback function as in Symfony's cookbook
$formModifier = function (FormInterface $form, $preparedOptions) {
$form->add($this->childIdentifier, ChoiceType::class, $preparedOptions);
};
And then the listener is built like this
$builder
->get('lang_switcher')
->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) use ($formModifier, $options) {
$preparedOptions = $this->prepareOptions($options);
$formModifier($event->getForm()->getParent(), $preparedOptions);
}
);
<script type="text/javascript">
function inputBtn(){
var input=document.createElement('input');
input.type="file";
input.name="img[]";
input.multiple="multiple";
//without this next line, you'll get nuthin' on the display
document.getElementById('target_div').appendChild(input);
}
</script>
<button id="ifile" onclick="inputBtn();">create</button>
<form action="test.php" method="post" enctype="multipart/form-data">
<div id="target_div"></div>
<input type="submit">
</form>

Using Javascript to send a keystroke in an input when a button is clicked

Is there any way using Javascript to send the "enter" aka keystroke "13" in an input when a button is clicked?
Details on why I want this:
Basically I have a car part look up tool that uses jQuery to actively post to a php file that searchs a MySQL DB, I wanted to make a few buttons with common car part OEMs, like; Chevrolet, Ford, Toyota etc.. I have the buttons doing they're thing when I click on them then change what is in the search field but it won't post to the php file until I press enter, so I wanted to hit two birds with one stone, click the button and it will enter 'chevrolet' in the search in put and then press enter for me all at once with one click of a button. =)
here is the code I am using to post data to the php file:
$(document).ready(function() {
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}return false;
}
$("input#search").live("keyup", function(e) {
clearTimeout($.data(this, 'timer'));
var search_string = $(this).val();
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}else{
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
});
UPDATE:
I was able to make it work with the following code:
Javascript:
$(".btn3").click(function() {
var e = $.Event('keyup');
e.which= 13;
$('#search').val($(this).val());
$('#search').trigger(e);
});
HTML:
<input type="button" class="btn3" id="CHEVROLET" value="CHEVROLET" />
I'm assuming you have a function that handles the event of a user pressing the 'enter' key in the search input. Simply give that function a name and have it fire on the button click as well!
The way to do what you are asking:
$('#buttonID').click(function(){
// Create a new jQuery.Event object with 'keydown' event specified.
var e = jQuery.Event( "keydown", { keyCode: 13 } );
// trigger (send) an artificial keydown event with keyCode 13
jQuery( "body" ).trigger( e );
});
Depending on the application, if it is to make it so that the form submits when a non-submit button is pressed then
$('#buttonID').click(function(){
$('#FormID').Submit();
});
would be the way to go.
Edit:
Alternatively to send the 'enter' command to the specific input box use:
$('#myInputId').trigger(jQuery.Event('keypress', {which: 13}));
You may need to replace which with keyCode depending on the version of jQuery you are using...
JSFiddle Demo
from the updated description though, sounds like there must be a form on the page, if you can determine its id (look through source for <form .. id="FormID" then it would be better practice to use the submit function as above:
$('#buttonID').click(function(){
$('#myInputID').val("Chevrolet"); // or however you are already doing this part
$('#FormID').Submit();
});
What you should do is split the Javascript from the button so your final result will be something like:
<script>
$(".btn3").click(function() {
$('#search').val($(this).val());
$('#search').trigger(jQuery.Event('keypress', {which: 13}));
});
</script>
<input type="button" class="btn3" id="Chevrolet" value="Chevrolet" />
<input type="button" class="btn3" id="Ford" value="Ford" />
<input type="button" class="btn3" id="Anotherone" value="Anotherone" />
What may be going wrong is you said you have multiple buttons, but keywords is a pretty generic id, which you may be repeating.. an ID must be unique or JS will not work correctly, if you want to perform a JS function for a group of things it is better to use the class, as this does not have to be unique.
so basically what the above does is waits for anything with class="btn3" in it to be clicked.
when that happens the input with id="search" gets filled with whatever the value= contains for what was clicked. Once that has happened the [enter] keypress is triggered inside the search input box.
This way, no matter which button gets pressed (Chevrolet, Ford or Anotherone) the search input box will get filled with the correct value. To add more buttons all you have to do is make sure they have class="btn3" and value="SOMETHING" and the above should work.
$(document).ready(function() {
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}return false;
}
$("input#search").live("keyup", function(e) {
clearTimeout($.data(this, 'timer'));
var search_string = $(this).val();
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}else{
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
// ADD THIS
$(".btn3").click(function() {
$('#search').val($(this).val());
search();
});
});
...
<!-- Fix inputs -->
<input type="button" class="btn3" id="Chevrolet" value="Chevrolet" />
<input type="button" class="btn3" id="Ford" value="Ford" />
<input type="button" class="btn3" id="Anotherone" value="Anotherone" />

Categories

Resources