I have a multi-lingual page where I want to display form validation error in the user's language. I use a hidden input to determine which language version the user is browsing like this: <input type="hidden" name="lang" id="lang" value="<?php echo $lang; ?>" />
The PHP side of the script works, but jQuery doesn't seem to realize which language is passed on. It displays the English error message no matter on which language site I am.
Here's the code (I removed the other form fields for length):
$(document).ready(function(){
$('#contact').submit(function() {
$(".form_message").hide();
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var lang = $("#lang").val();
var name = $("#name").val();
var dataString = {
'lang': lang,
'name': name
}
if (name == '') {
if (lang == 'de') {
$("#posted").after('<div class="form_message"><p><span class="error">Fehler:</span> Bitte gib deinen Namen an!</p></div>');
} else {
$("#posted").after('<div class="form_message"><p><span class="error">Error:</span> Please enter your name!</p></div>');
}
$("#name").focus();
$("#name").addClass('req');
} else {
$("#loading").show();
$("#loading").fadeIn(400).html('<img src="/img/loading.gif" />Loading...');
$.ajax({
type: "POST",
url: "/contact-post.php",
data: dataString,
cache: false,
success: function(html){
$("#loading").hide();
$("#posted").after('<div class="form_message"><p>Thank you! Your contact request has been sent.</p></div>');
$("#contact input:submit").attr("disabled", "disabled").val("Success!");
}
});
}return false;
}); });
The problem seems to be somewhere in the nested if statement. Does jQuery / javascript even recognize nested ifs? And if yes, why is it not working?
Does jQuery / javascript even recnogize nested ifs?
Yes they do
One thing worth checking that would cause this behaviour is that you don't have any other elements on your page with id = lang. If there are, your $("#lang") selector will only find the first one, and if that's not your hidden input it won't work as you expect.
Javascript is case-sensitive, and perhaps the value of your #lang element is in a different case. You can force it to be lowered like this...
var lang = $("#lang").val().toLowerCase();
Why wouldn't it recognize nested if's?
Can you include the HTML for the page? There doesn't appear to be anything wrong with this javascript at all - so I have a feeling the issue is with the rest of the page.
Barring that, put an alert(lang) in right before your if statement to see what it is set to. My guess is that it will not be set to the value that you think it should be set to.
Check the value
alert("'" + lang + "' :" + lang.length);
Related
I'm trying to add a review snippet to a webpage after retrieving the corresponding data-id from the database. Unfortunatly the snippet doesn't work properly if I add the snippet like shown below. The snippet works fine if it is hardcoded in html but not if I add it in javascript or if I put the snippet without a data-id and then try to append the data-id attribute with the correct id.
I've tried loading my ajax call to the database in a script next to the div's location to then simply use document.write() but without success. The snippet in use is a review snippet from Mobials.
Help is greatly appreciated.
<div id="mobials"> </div>
<script type="text/javascript" src="//api.mobials.com/assets/js/api/v1.js"></script>
<script type="text/javascript" src="https://mobials.com/assets/js/api/review.min.js"></script>
function Submit() {
if (validateInputs()) {
$.ajax({
type: "GET",
url: "#ViewBag.urlApi" +"LocationDetails?zipcode=" + $("#ZipCodeLoc").val() + "&format=JSON&authoriazation={"+"#ViewBag.ApiKey"+"}",
dataType: "jsonp",
traditional: true,
success: function (data) {
$("#events").empty();
$("#logos").empty();
$("#openingHours").empty();
locationDetails = JSON.parse(data);
//Customer Reviews
var isMobial = false;
$.each(locationDetails.Reviews, function (key, value) {
if(key == "Type" && value == 1){
isMobial = true;
$("#consumerAffairs").hide();
}
if(key == "ReviewCode" && isMobial){
var mob = document.getElementById("mobials");
mob.innerHTML += '<div class="mobials-root" data-id="'+value.reviewcode+'" data-language="en" data-type="badge" data-size="200"></div>';
}
});
}};
}
}
EDIT: This line in my .html:
<div class="mobials-root" data-id="someId" data-language="en" data-type="badge" data-size="200"></div>
Looks like this when loaded:
<div class="mobials-root" data-id="someId" data-language="en" data-type="badge" data-size="200" data-tracker="1" id="mobial-root-1"><img src="https://s3.amazonaws.com/mobials.com/api/badges/read_reviews/en/174_174_4.7_70.png"></div>
You can't use document.write() with ajax calls.
document.write() will work "as expected" only as long as the document is open. As soon as the browser recognizes that the document is loaded completely, the document is closed.
Subsequent calls to document.write() will replace the document rather than append to it.
Edit: but looking at your code, I don't see document.write() at all.
I am trying to build a quiz environment. The user selects an answer and then clicks submit. Upon submit, the following jquery is called:
$(document).ready(function() {
$('.btn-large').click(function() {
$.post("correct_quiz.php",
{
choices : $('input[name=choice][type=radio]:checked').serialize()
},
function(data) {
var temp = '#correct' + data;
var temp2 = '#correct3';
$(temp).show(); // Make the wrong/right icons visible
});
});
});
This jquery makes a green or red icon appear, based on whether the answer was correct or not. The correct_quiz.php script contains:
<?php
$root = "/users/stadius/maapc/public_html/";
include($root . "connect_to_database.php");
$choices = $_POST['choices']; // This will for example output "choice=3"
echo substr($choices,7,7); // This will then output "3"
?>
I ran into a problem, when I try the above jquery code with variable temp2 the script works like I want. But when I try it with variable temp it doesn't. When I debug, I see that they contain exactly the same string though: both are '#correct3' (when I choose the 3rd answer).
So why is this not working when I use variable temp, and is working when using temp2?
I think your problem is in this line:
echo substr($choices,7,7);
Try to use:
$list = explode('=', $choices);
echo $list[1];
instead of substr
We have approval with our client, just a heads up to cover me in any way.
We are needing to modify some of the code in a clients site if a cookie is seen on their computer, the client's site is in ASPX format. I have the first part of the code created, but where I am getting stuck is this:
I need to remove the last 2000 characters (or so) of the body of the page, then append the new HTML to it.
I tried:
$('body').html().substring(0, 10050)
but that doesn't work, I also tried copying that HTML (which did work) and put it back with the new code, but it created a loop of the script running.
Any suggestions on what I should do? It has to be javascript/jQuery sadly.
//////// EDIT ////////////
My script is brought in by Google Tag Manager, and added to the page at the bottom, then my script runs, this is what was causing the loop in the script. Basically, here is the setup:
My Script on my server is loaded into the client site using Google Tag Manager, added to the bottom of the page. From there it is able to execute, but when doing this, it creates a loop of adding the Google Tag Manager script, causing my code to re-add, causing it to re-execute again.
The client is not willing to do anything, he has pretty much told us to just figure it out, and to not involve his web guy.
This is the code straight from their site I am trying to edit.
<script language="JavaScript">
jQuery(function($){
$('#txtPhone').mask('(999) 999-9999? x99999');
$('#submit').click(function(){CheckForm();});
});
function CheckForm(theForm){
if (!validRequired($('#txtfirst_name'),'First Name')){ return false; }
if (!validRequired($('#txtlast_name'),'Last Name')){ return false; }
if (!validRequired($('#txtEmail'),'E-Mail Address')){ return false; }
if (!validEmail($('#txtEmail'),'E-Mail Address',true)){ return false; }
if (!validPhone($('#txtPhone'),'Phone Number')){ return false; }
var dataList='fa=create_lead';
dataList += '&name=' + $('#txtfirst_name').val();
dataList += '&lastname=' +$('#txtlast_name').val();
dataList += '&email=' + $('#txtEmail').val();
dataList += '&phone=' + $('#txtPhone').val();
dataList += '&vid=' + dealerOnPoiVisitId;
dataList += '&cid=' + dealerOnPoiClientId;
dataList += '&leadType=9';
dataList += '&leadSrc=32'; ////////////////////// THIS IS WHAT I AM ATTEMPTING TO CHANGE /////////////////////////
dataList += '&contactname=' + $('#contactname').val();
dataList += '&comment=' + encodeURIComponent($('#txtComments').val());
dataList += '&dvc=' +encodeURIComponent(DealerOn_Base64.encode($('#txtfirst_name').val() + $('#txtEmail').val()));
var lid=1;
$('#submit').prop('disabled', true);
$.ajax({
url:'/lead.aspx',
data: dataList,
dataType: 'json',
success: function(data){
$('#submit').prop('disabled', false);
lid=data.leadid;
if (lid > 1){
$('#submit').prop('disabled', false);
var jqxhr = $.post('/lead.aspx?fa=complete_lead&leadid=' + lid , function() {
window.location.href='/thankyou.aspx?name=' + $('#txtfirst_name').val() + '&lid=' + data.leadid;
});
}
},
error: function(request,error) {
$('#submit').prop('disabled', false);
}
});
}
</script>
This is the page on the site: www.moremazda.com/contactus.aspx
You have to add the HTML back:
var html = $('body').html().substring(0, 10050);
$('body').html(html);
Note that doing this, and just randomly removing chunks of HTML is not good practice, and could lead to a number of problems.
Technically you should be able to do this:
var bodyHTML = $('body');
bodyHTML.html(bodyHTML.html().substring(2000));
But as I pointed out in my comment above, that is a REALLY BAD idea.
If you have access to the HTML to the page, wrap the code you want to replace in a identifiable tag and remove that. I.e.:
<div id="tobeRemoved">Lorem Ipsum</div>
<script>
$('#toBeRemoved').empty();
</script>
If you can't edit the HTML, but you know that it is always the last script tag, you could do something like this:
var scripts = $('script');
scripts.get(-1).remove;
Alright, so I'm making a form validation everything is good in this JS, but now I'm facing a problem in the output, I am trying to display all the chosen data. So I used the action attribute and called the following function:
function funcs()
{
var favor = document.reg.favor[selectedIndex].value; //Select input
var fname = document.reg.fname.value; // text input
var lname = document.reg.lname.value; // text input
var email = document.reg.email.value; // text input
var pass = document.password.value; //text input
for(i=0;i<document.reg.rad.length;i++)
{
if(document.reg.rad[i].checked == true)
{
var rad = document.reg.rad[i].value; // Radio input
}
}
if(document.reg.bike.checked == true)
{
var bike = document.reg.bike.value; //CheckBox input
}
if(document.reg.car.checked == true)
{
var car = document.reg.car.value; //CheckBox input
}
document.write('<head><link type="text/css" rel="stylesheet" href="registrationtable.css"/></head><body>');
document.write("<div class = 'team'>");
document.write('<table>');
document.write("<tr><td> שם פרטי: </td><td>" + fname + "</td></tr> <tr><td> שם משפחה: " + lname + "</td></tr> <tr><td> אימייל: " + email + "</td></tr> <tr><td> סיסמא: " +pass +"</td></tr>");
document.write("<tr><td> השחקן האהוב עליך הוא " + favor +"</td></tr>");
document.write("</table>");
document.write("</div></body>");
}
Here's the form header:
<form name ="reg" action ="Javascript:funcs()" onsubmit ="return checkValidation()">
I'd like to clear that all the other javascript code is working perfectly, it must be something with this function.
When I'm pressing the send button, it won't do anything. Anyone knows whats the problem?
Thanks in advanced.
You can't shouldn't have a javascript function in your action attribute, it needs to be a URI. You can just call the funcs onsubmit if validation succeeded.
As Aquinas has shown that calling a javascript function in the action attribute is in fact possible, it is advised that you not put js code in the action attribute.
As I suspected. One problem is this line:
var favor = document.reg.favor[selectedIndex].value;
It should be
var favor = document.reg.favor[document.reg.favor.selectedIndex].value;
And your second problem is this:
var pass = document.password.value;
Should be:
var pass = document.reg.password.value;
See updated fiddle: http://jsfiddle.net/x7SBy/1/
Finally, you should use Firefox and download Firebug. It is invaluable for debugging JS problems like this.
Edit: There are other problems with your JS that I won't get into in detail, but in general you don't want to use document.reg.password, because of issues like this. You should really use document.getElementById. FYI.
It looks like you are trying to validate a form, then if valid call the funcs function to alter HTML on the page.
Maybe something like this:
<form name="reg" action="" onsubmit="checkValidation()">
Then a checkValidation function to pause form submission and if valid, call the funcs function:
function checkValidation(e) {
e.preventDefault();
if (checkValidation()) {
funcs();
}
}
But if this is the case, your funcs function should not be writing <head> tags and such. Maybe you could just add HTML to the body instead of trying to lay a new HTML document into the DOM with javascript.
Alternate solution:
function checkValidation() {
... do your validation
return true; // or false if invalid
}
Then use a real HTML page/resource in your action tag of the form.
I'm trying to submit a form using Jquery's ajax. It has got a few textboxes, some checkboxes, and a multiple options' dropdown (i.e multiple options can be selected).
Someone here told me that I can get values of all selected checkboxes using
$("input:checkbox[name=type]:checked")
Then I can loop through all the values returned by the above code, assign them to an array like this:
var types=new Array();
$.each(cboxes, function()
{
types[types.length]=$(this).val();
}
);
And try to submit the form using this:
var someField=$("#someField").val();
var someField2=$("#someField2").val();
var data={field1 : someField, field2=someField2, s_types:types};
$.post("signup.php?type=p",types);
But that doesn't work, specifically the checkboxes don't get submitted correctly. How can I make it work?
It's not necessary to iterate over each field to get the form values. jQuery has a method to serialize form inputs into a querystring. You can do this:
$.ajax({
url: "mybackend.php",
data: $("#myForm").serialize(),
success: function(e) { // do something on success },
error: function(e) { // do something on error }
});
Remember that javascript posts always send data in UTF-8 format, so be sure you're expecting that on the backend if you plan to send text with international characters.
I recommend using a plug-in to do that. Have a look at this form plug-in. It also can integrate nicely with validation plug-in.
The default jQuery $.param doesn't handle arrays (by design), so you can't use $.serialize as it is. Use either a plugin, like suggested in kgiannakis' answer, or overwrite the $.param function so it'll handle arrays properly:
function($) {
$.param = function(a) {
var s = [];
if (a.constructor == Array || a.jquery)
jQuery.each(a, function() { s.push( encodeURIComponent(this.name) + "=" + encodeURIComponent( this.value ) ); });
else
for (var j in a)
if (a[j] && a[j].constructor == Array) jQuery.each( a[j], function(){ s.push( encodeURIComponent(j) + "[]=" + encodeURIComponent( this ) ); });
else s.push(encodeURIComponent(j) + "=" + encodeURIComponent(a[j]));
return s.join("&").replace(/%20/g, "+");
};
})(jQuery);
...and then use $.serialize, like suggested by Danita.