Javascript to display labels on the button with the same class - javascript

Here's a simple question:
On the page there are two javascript.
The first script gets JSON and used it to build multiple forms with buttons:
$.getJSON("http://api.server.com/my/?callback=?",
function(data){
var results = [];
$.each(data['results'], function(i, result) {
results.push("<div class='accordion-group span4'><div class='accordion-heading'>Video Frame<blockquote><a href='http://server.com/video/?my=" + result.File + "' target='_blank'><img src='http://jpg.server.com/" + result.File + ".jpg' class='img-polaroid'/></a><p>" + result.ListId + "</p><small>" + result.OwnerId + "</small><small>" + result.updatedAt + "</small> </blockquote><a class='accordion-toggle' data-toggle='collapse' data-parent='#accordion2' href='#" + result.File + "'>Share video</a></div><div id='" + result.File + "' class='accordion-body collapse'><div class='accordion-inner'><form class='share_file_form'>Set list<input name='nd' id='user_id' type='hidden'><input name='file' value = '" + result.File + "' type='hidden'><div class='list'></div><input type='text' placeholder='New list'><div class='modal-footer'><button class='share_file_submit'>Share video</button></div></form><div id='user_info_result'></div></div></div></div>");
});
$('#mytile').html(results.join(""));
}
);
The second script is a response by pressing a button on the form of constructing the first script:
$(document).on('click', '.share_file_form', function(event) {
$(this).validate({
submitHandler: function(form) {
$.ajax({
type: "GET",
url: "http://api.server.com/set/",
timeout: 20000,
data: $(form).serialize(),
beforeSend: function() {
$(".share_file_submit").attr("disabled", true);
$(".share_file_submit").html("Send <img src='http://src.server.com/loadr.gif' border='0'/>");
},
success: function(msg){
console.log("Data Saved: " + msg);
$("#share_file_submit").attr('disabled', false);
$("#share_file_submit").html("Share video");
$("#user_info_result_2").html(msg);
},
error: function(msg){
//////////////// $('#user_info_result_2').html("<div class='alert alert-error span3'>Failed from timeout. Please try again later. <span id='timer'></span> sec.</div>");
}
});
}
});
});
Everything works, but at the time of the second script, the inscription appears on the buttons of all forms, and I need only one button, which I click.

The problem is this line:
$(".share_file_submit").html("Send <img src='http://src.server.com/loadr.gif' border='0'/>");
It sets the html for all elements with the "share_file_submit" class on the entire page. You can fix it by adding a context to the selector:
$(".share_file_submit", $(form)).html("Send <img src='http://src.server.com/loadr.gif' border='0'/>");

If you really want to use validate plugin properly you shouldn't initialize it within a click handler.
Should be initializing right after the form building code.
Within $.getJSON
$('#mytile').html(results.join(""));
$('.share_file_form').validate(/* options*/);
The submitHandler will over ride the default submit event of the form and validation will be active while user fills out form.
To fix button issue:
submitHandler: function(form) {// form is current form elemnt
$.ajax({
beforeSend:function(){
/* look within form for button*/
$(form).find(".share_file_submit").prop('disabled',true);
})
});
Now if user uses Enter key you aren't relying on a click event to prevent submittal by browser default

Related

jQuery AJAX running twice on click

I'm trying to make two Ajax calls in one page using jQuery. The first Ajax runs successfully and produces results. Second Ajax is supposed to fire up on button click and show the result, but it runs twice every time I click on the button. And initially on the first time clicking on the button, I have to click twice before it produces a result. Here's what I'm trying to do:
function showPicture() {
$("button").click(function() {
var id = this.id;
$.ajax({
type: 'POST',
url: 'displaySearch.php',
data: {'getTile': $(this).val()},
success: function(data) {
console.log(id);
$("#" + id).replaceWith("<img src=" + data + " />");
}
});
});
}
Here's my button:
<button id=" . $count . " onclick=showPicture() value=" . htmlentities($result['Poster']) . ">Click Me!</button>
I have seen similar questions on Google but I cannot figure out what the problem is. Any help would be greatly appreciated.
You have 2 onClick handlers, somewhat:
onClick
$("button").click()
Remove one of the handlers.
Example
function showPicture(id) {
$.ajax({
type: 'POST',
url: 'displaySearch.php',
data: {'getTile': $(this).val()},
success: function(data) {
console.log(id);
$("#" + id).replaceWith("<img src=" + data + " />");
}
});
}
<button id=" . $count . " onclick=showPicture(" . $count . ") value=" . htmlentities($result['Poster']) . ">Click Me!</button>
Your function 'showPicture' which you are calling from the html attribute below
<button id=" . $count . " onclick=showPicture()
is calling your function as you would expect.
but the function showPicture() itself is then binding a onclick event
function showPicture() {
$("button").click(function() { <------- this
......
So it is being hit twice as you have the attribute onclick and the even binding onclick.
The event click is on all html buttons.
What you should do: Remove the binding in the function to all buttons
function showPicture(caller) {
var id = $(caller).attr("id");
var val = $(caller).val();
console.log(id);
console.log(val);
$.ajax({
type: 'POST',
url: 'displaySearch.php',
data: {'getTile': val },
success: function(res) {
--you are replacing the button with an image... or something like that
$("#" + id).replaceWith("<img src=" + res+ " />");
}
});
}
html
<button id=".$count." onclick="showPicture(this)" value=".htmlentities($result['Poster']).">Click Me!</button>

jQuery click event is not working in first click

I using a code on my page. Like this:
$('#language_id').change(function () {
var urli = 'https://example.com/php/get_arch.php?language_id=' + language_id;
$.ajax({
type: "GET",
url: urli,
dataType: 'json',
success: function(response){
var options = '';
$.each(response.archs, function() {
options += '<option value="' + this.arch_id + '">' + this.name + '</option>';
});
$('#arch_id').html('<option value="0">- ' + selachitecture + ' -</option>'+options);
$('#arch_id').attr('disabled', false);
}
});
});
$('#arch_id').change(function(){
var version_id = $('#version_id :selected').val();
$('#selectBoxInfo').load('https://example.com/dl.php?fileName=' + arch_id + "&lang=" + lang);
return(false);
});
$('body').on('click', '.buttond a', function() {
alert("new link clicked!");
$("a").removeAttr("onclick");
});
I explain my code: when selecting an optional, it will create a button "Download". This button load by Ajax. I don't want feature pop-up of this button.
So, I tried to prevent this button turn on the pop-up.
The problem is: at first click in button, my Javascript is not working. It only works from the second click.
I don't know problem at here. I using 'on' to listen to all event.
replace your code with this code ..
$('#selectBoxInfo')
.load('https://example.com/dl.php?fileName=' + arch_id+"&lang="+lang
,function(){
$("a").removeAttr("onclick");
}
);

Fire jQuery event on enter key press?

I'm trying to submit a rails form using jQuery (Which I know little about) and have had success in setting up a form to submit on clicking the submit button and run a callback(I believe this is the correct terminology?), but I would also like to make it work when just hitting enter.
As it stands, hitting enter will submit data to the database but will not run the commands to append the div or clear the text field. How could I make this happen so it works the same for the enter key as it does the submit button? I've tried to wrap the code inside a function that will run when enter is hit but having no luck!
function runScript(e) {
if (e.keyCode == 13) {
msg = json.msg;
foreign = json.foreign_speaker;
msg_translated = json.msg_translated;
//The HTML that we will append to the document.
html = "<div class='msg msg" + foreign + "'>" + msg +
"</div> <div class='msg msg" + foreign + "-translation'>" + msg_translated + "</div>"
// Append new message.
$('.chatmessages').append(html).fadeIn('fast');
scrollToBottom(500)
// Clear form with jquery.
$('#message_msg').val('');
$('#message_foreign_speaker').attr('checked', false);
}
}
I tried that with no luck.
My current, button-working, JS file:
var scrollToBottom = function(anim){
var myDiv = $(".wrap");
myDiv.animate({ scrollTop: myDiv[0].scrollHeight - myDiv.height() }, anim);
};
$(document).ready(function(){
scrollToBottom(0)
//JS to POST form
$('.submit').click(function() {
var valuesToSubmit = $('.msgform').serialize();
$.ajax({
type: 'POST',
url: window.location.href + '/messages', //sumbits it to the given url of the form
data: valuesToSubmit,// { chat_id, <%= #chat.id %> },
dataType: "JSON", // you want a difference between normal and ajax-calls
})
.done(refresherFunc)
.fail(function(){
alert("Error sending message. It would be nice to make this a flash error.");
});
return false; // prevents normal behaviour
})
});
var refresherFunc = function(json) {
// Get debugging goodies.
console.log(json);
// Set variables with JSON object data
msg = json.msg;
foreign = json.foreign_speaker;
msg_translated = json.msg_translated;
//The HTML that we will append to the document.
html = "<div class='msg msg" + foreign + "'>" + msg +
"</div> <div class='msg msg" + foreign + "-translation'>" + msg_translated + "</div>"
// Append new message.
$('.chatmessages').append(html).fadeIn('fast');
scrollToBottom(500)
// Clear form with jquery.
$('#message_msg').val('');
$('#message_foreign_speaker').attr('checked', false);
}
Catch your form submit event with jQuery's submit() function and return false inside it. This function will be called any way you submit the form (clicking on submit button or pressing enter key). Returning false will prevent the browser from completing the form sumbittion which lets you do whatever you want with it.
See example: http://jsfiddle.net/vgk4wu46/

List of two JSON requests

I do not understand how to do the right thing.
With this query I get a JSON with the file names:
$.getJSON("http://api.server.com/my/?callback=?",
function(data){
var results = [];
$.each(data['results'], function(i, result) {
results.push("<div class='accordion-group span4'><div class='accordion-heading'>Video Frame<blockquote><a href='http://server.com/video/?my=" + result.File + "' target='_blank'><img src='http://jpg.server.com/" + result.File + ".jpg' class='img-polaroid'/></a><p>" + result.ListId + "</p><small>" + result.OwnerId + "</small><small>" + result.updatedAt + "</small> </blockquote><a class='accordion-toggle' data-toggle='collapse' data-parent='#accordion2' href='#" + result.File + "'>Share video</a></div><div id='" + result.File + "' class='accordion-body collapse'><div class='accordion-inner'><form class='share_file_form'>Set list<input name='nd' id='user_id' type='hidden'><input name='file' value = '" + result.File + "' type='hidden'><div class='list'></div><input type='text' placeholder='New list'><div class='modal-footer'><button class='share_file_submit'>Share video</button></div></form><div id='user_info_result'></div></div></div></div>");
});
$('#mytile').html(results.join(""));
}
);
With this query I get a JSON with the tag names:
$.getJSON("http://api.server.com/list/?callback=?",
function(data){
var results = [];
$.each(data['results'], function(i, result) {
results.push("<label class='radio'><input type='radio' name='list' id='" + result.List + "' value='" + result.List + "' checked>" + result.List + "</label>");
});
$('.my_list').html(results.join(""));
}
);
In the end, I need to display a list of files. Next to each file should to show a form with a file name and a list of tags:
$(document).on('click', '.share_file_form', function() {
$('.share_file_form').validate({
submitHandler: function(form) {
$.ajax({
type: "GET",
url: "http://api.server.com/set/",
timeout: 20000,
data: $(form).serialize(),
beforeSend: function() {
$(".share_file_submit").attr("disabled", true);
$(".share_file_submit").html("Send <img src='http://src.server.com/loadr.gif' border='0'/>");
},
success: function(msg){
console.log("Data Saved: " + msg);
$("#share_file_submit").attr('disabled', false);
$("#share_file_submit").html("Share video");
$("#user_info_result_2").html(msg);
},
error: function(msg){
//////////////// $('#user_info_result_2').html("<div class='alert alert-error span3'>Failed from timeout. Please try again later. <span id='timer'></span> sec.</div>");
}
});
}
});
});
All of this works.
The question is how to make sure that each form will work separately?
Now only works the first form. If you press the button on the other forms will still work the first form.
Your mistake is in the way you identify the form on which the user clicked. The following line is the problem:
$('.share_file_form').validate({
Independent of what you clicked on, you always will get the first form with this selector.
Here is what you need instead:
$(document).on('click', '.share_file_form', function(event) {
$(event.target).validate({
submitHandler: function(form) {
hmm. I 'think' I know what you want..
how about wrapping the second call in a method, or perhaps both, ala.
function fireJSON(){
var func1 = function(){
//your first json code
func2(); // call your second json code
}
var func2 = function(){
// second json code
}
return {
func1: func1
}
}
fireJSON().func1();

using colorbox over another colorbox using jquery/ajax

i have a page where i'm using a with id="emailfrnd", from the following script i successfully implemented the colorbox:
<script type="text/javascript">
$(document).ready(function(){
$("#emailfrnd").colorbox({
inline: true,
href:"#ef",
close:"",
opacity:0.95,
onClosed:function(){
//window.parent.location.reload(true);
}
});
});
</script>
now the new colorbox contains a form with a send button in it of id "emailfrnd_submit" now i had written some validations using the jquery & ajax and if there are no errorMessages i'll get another colorbox and the code is as follows:
if (errorMessage == '') {
$.ajax({
type: 'POST',
url: root_url + '/services/services.php?method=emailfrnd',
data: "name=" + name + "&email=" + email + "&message=" + message,
async: true,
success: function (data) {
if (data == 1) {
$("#emailfrnd_submit").colorbox({
inline: false,
close: "",
html: "<div style='height:230px;width:400px;display:block;'><p style='color:black;font:16px verdana;'>Your email was successfully sent.</p><br/><p style='color:gray; font:16px verdana;'>Thank you for telling your friend</p><div id='emailfrnd_sub' style='width: 50px;margin-top:30px;float: right;'><input type='submit' value='OK' name='emailfrnd_submit' id='emailfrnd_sub' class='redbut' style='float:right;position:absolute;right: 198px;margin-top: 0px;color:white;'></div></div>",
opacity: 0.95,
onClosed: function () {
//window.parent.location.reload(true);
}
});
//window.location.assign("../index.php");
} else {
alert('mail not send');
}
}
});
} else {
alert(errorMessage);
}
});
upto now i succeed in getting the things as i want, here after doing the validations and onclick the send button according to this code a new colorbox with the html content as above is coming, here i have a Ok button here, i want to make that button as the closing button of this colorbox. how can i get that functionality for the ok button here??
anyone help is much appreciated....thanks in advance.....
You don't need 2 colorboxes to do it.
Why don't you simple create a div which class is message_content and you update it's text according to the ajax status ?
It's much better.
Example:
html:
<div id="colorbox_content"> //#todo: change to colorbox id
<form id="your_form"> //#todo: change according to your form id
</form>
<div class="message_content">
<p class="message"></p>
<span class="close">Close</span>
</div>
</div>
js:
/**
* Close message
*/
jQuery('#colorbox_content').on('click', '.close', function() {
jQuery(this).closest('#message_content').slideUp();
});
/**
* On form submit
*/
if (errorMessage == '') {
$.ajax({
type: 'POST',
url: root_url + '/services/services.php?method=emailfrnd',
data: "name=" + name + "&email=" + email + "&message=" + message,
async: true,
success: function (data) {
if (data == 1) {
var message = "Your email was successfully sent.";
//window.location.assign("../index.php");
} else {
var message = "Your email was successfully sent.";
}
jQuery('#colorbox_content').slideDown().find('.message').text(message);
}
});
} else {
alert(errorMessage);
}
Update based on this comment:
If you want the same funcionality for different buttons you have to use the same class for them.
here's what do you need.
demo
I changed some ids to classes so you don't need 2 events with the same code.
And here's the las version.
You can see that you can store your options for each kind of colorbox and then pass them thrue parameter.
i got the answer and the fiddile shows how to do it.....::::)))))
http://jsfiddle.net/srinivaswaterdrop01/4vuDC/189/

Categories