I have a Javascript problem that I cannot find the answer to. Hope you can help me.
I have this element called 'scanValue', that has an onFocus and an onBlur trigger:
<input name="scanValue" class="searchFormText" style="width: 220px; font-size: 22px;" onfocus="onFocusElement(this)" onblur="onBlurElement(this)" type="text" maxLength="20" value="510210006823414"/>
If I tab out of the field the onBlurElement() function is called as expected:
function onBlurElement(object) {
alert('onBlurElement: Start blur on ' + object.name + ' (old val = ' + prevObjectVal + ', new val = ' + object.value + ')');
if (object.value !== prevObjectVal) {
check(object);
var checkFcn = 'check' + object.name;
var fcnParms = [object.value];
var fcn = window[checkFcn];
alert('onBlurElement: check if ' + checkFcn + ' is a function: ' + (typeof fcn));
if (typeof fcn == 'function') {
alert('fcnParms length = ' + fcnParms.length + '. ToString= ' + fcnParms.toString());
alert('fcnParms[0] length = ' + fcnParms[0].length + '. ToString= ' + fcnParms.toString());
fcn.apply(fcn, fcnParms);
}
}
}
Now this dynamic function call (fcn.apply()) should call the function 'checkscanValue(val)', but nothing happens. EXCEPT when I add an alert() to this function OR if I fire up the IE standard developer tools. In other words, if I track or debug the checkscanValue() function everything works, otherwise is does nothing. I've tried several different things, but nothing seems to work. I doubt this could have anything to do with the form being submitted with method post, but maybe someone could help me on that.
Code for the checkscanValue() function:
function checkscanValue(val) {
console.info('checkscanValue: start function');
document.forms[0].airNumber.value = 'test';
// Check if the scanned value is valid for submitting the form
if (val[0].length === 15) {
document.forms[0].submit();
}
}
Everything is working fine except that the "val" parameter that you are passing to the checkscanvalue function is the string that the user entered or is there by default.
So val[0] returns the first character of the string whose length can't be 15 and hence the check fails and nothing happens.
hope it helps!
This seems to answer my question: 'console' is undefined error for Internet Explorer
I've been using the function console.info() which is undefined if the console window of IE was never opened. This caused the function to stop. If I replaced it with an alert() it obviously worked and if I opened the console of IE, the console.info function was defined.
Related
I've got some troubles with this code.
$('body').on("keypress", ".message", function(e) {
if ( e.keyCode == 13 && $(".message").val().length > 0 ) {
input = $(".message");
// Check for join command.
if (input.val().substr(0, 5) == "/join") {
// Get channel
channel = input.val().substr(7, input.val().length);
// APPEND NEW TAB
$("ul.nav-tabs li").after('<li><a href="#' + channel + '" aria-controls="#' + channel + '" role="tab" data-toggle="tab">#' + channel + '</li>');
$('.tab-content').append('<li class="tab-pane log" role="tab-pane" id="' + channel + '" data-channel="' + channel + '"><div class="Topic">Hej och välkommen till #' + channel + '.</div><ul class="Messages"></ul><input type="text" name="message" id="message" autocomplete="off" class="message sendValue"></li>');
$(".nav-tabs li").children('a').last().click();
}
log('<strong>Du</strong>: ' + input.val());
send( input.val() );
$(".message").val('');
}
});
The keypress event doesn't react on the dynamically added input, I read something about adding the on event after added, because of that this code runs when the dom is loaded.
So my question is: how can I make this so the dynamic inputs works aswell?
You're already using .on so I think it is working properly and that your real problem is this:
input = $(".message");
which you need to change to this:
var input = $(this);
otherwise you'll always be dealing with the first input even if there's multiple on the page. Also you can use inspect element > console to debug these problems easier. For example if you add:
$('body').on("keypress", ".message", function(e) { console.log(e);
to your script you would have seen that the event handler is working fine and that your problem was further down.
(also change $(".message").val(''); to input.val('');)
My previous problem has been fixed, now I need to ask how to keep a textarea from resetting its input after a form is submitted. Here is the jsFiddle: http://jsfiddle.net/rz4pnumy/
Should I change the form in the HTML?
<form id="form1" method="GET">
(the form does not go into a php file or anything else, i'm using it to submit the textarea input and use the variables I made using jQuery to make a paragraph on the same page)
or something in the JS?
$(document).ready( function () {
$('#form1').on('submit', function (event) {
// If the form validation returns false, block the form from submitting by
// preventing the event's default behaviour from executing.
if (!validate()) {
event.preventDefault();
}
if(validate()) {
var adjective1 = $('#adjective1').val();
var adjective2 = $('#adjective2').val();
var pluralnoun = $('#plural-noun').val();
var verb1 = $('#verb1').val();
var edibleobject = $('#edible-object').val();
var monster1 = $('#monster1').val();
var adjective3 = $('#adjective3').val();
var monster2 = $('#monster2').val();
var verb2 = $('#verb2').val();
$('body').append(
'<div id="para">' +
'<p>Rain was still lashing the windows, which were now ' + adjective1 +', but inside all looked bright and cheerful. ' +
'The firelight glowed over the countless ' + adjective2 + '' + pluralnoun + ' where people sat ' + verb1 + ', talking, ' +
'doing homework or, in the case of Fred and George Weasley, trying to find out what would happen if you fed a ' + edibleobject +' to a ' + monster1 + '.' +
'Fred had "rescued" the ' + adjective3 + ', fire-dwelling ' + monster2 + ' from a Care of Magical Creatures class and it was now ' + verb2 + ' gently ' +
'on a table surrounded by a knot of curious people. </p>' +
'</div>'
);
}
});
function validate() {
var success = true;
$('.input').each(function(i, item) {
if ($(item).val() === "")
{
console.log("Missing textarea input");
success = false;
$(item).attr("style","border:1px solid red;");
//note it will overwrite your element style in all Input class
}
else
{
$(item).removeAttr('style')
// to remove border
}
});
return success;
}
});
The contents get emptied after pressing submit and I only see the completed paragraph for a split second.
You need to prevent the default event handler from executing whether validate passes or not, so you need to remove the if statement around the event.preventDefault() call. The preventDefault is the function that is keeping the from from submitting and re-loading your page.
Also, your Fiddle was not set to jQuery (it was set to no-library) so that may have also been causing you issues during your testing.
Edited for example of what I'm talking about:
$('#form1').on('submit', function (event) {
// block the form from submitting by
// preventing the event's default behaviour from executing.
event.preventDefault();
if(validate()) {
var adjective1 = $('#adjective1').val();
var adjective2 = $('#adjective2').val();
var pluralnoun = $('#plural-noun').val();
... etc ...
I would use php and set a variable to the GET value of the textarea and set the value of the textarea to that variable
I need the values of the name, address, size, and topping fields to appear in a text box. Without problems the name and address appears correctly. However I can't seen to get the size function to work. It is a radio button, and thus I need only one size to appear. I haven't even tried an if else for the checkbox yet. Here is my code
<html>
<head>
<script>
function pizza() {
document.pizzaboy.comments.value = "Name:" + " " + pizzaboy.name.value + "\n" + "Address:" + " " + pizzaboy.address.value + "\n" + document.getElementById("small").value + document.getElementById("medium").value + document.getElementById("large").value + "\n" + pizzaboy.toppings.value;
{
var rslt = "";
if (document.pizzaboy.size[0].checked) {
rslt = rslt + "Size=Small\n";
} else if (document.pizzaboy.size[1].checked) {
rslt = rslt + "Size=Medium\n";
} else rslt = rslt + "Size=Large\n";
return rslt;
}
}
</head>
The second Javascript bracket might be throwing you an error, keeping your code from running correctly.
In this post, several (more general) ways to get values of radio buttons are explained:
Checking Value of Radio Button Group via JavaScript?
The first answer is using jQuery, but the following answers will help you i think.
You should try this. Answer here if you need further assistance.
Ive got some javascript im using to validate a form which works fine but I now need to add a checkbox which needs to be checked before the form submits. The name of the checkbox is terms in the html and ive managed to get it to not submit the form using the code below.
$(document).ready(function(){
$("#sendmail").click(function(){
var valid = '';
var isr = ' is required.';
var name = $("#name").val();
var mail = $("#mail").val();
var subject = $("#subject").val();
var country = $("#country").val();
if( !$("#terms").is(":checked") ){
valid += '<br />Please accept the terms and conditions.';
}
if (name.length<1) {
valid += '<br />Name'+isr;
}
if (!mail.match(/^([a-z0-9._-]+#[a-z0-9._-]+\.[a-z]{2,4}$)/i)) {
valid += '<br />A valid Email'+isr;
}
if (subject.length<1) {
valid += '<br />Website Link'+isr;
}
if (country.length<1) {
valid += '<br />Country'+isr;
}
if (valid!='') {
$("#response").fadeIn("slow");
$("#response").html("Error:"+valid);
setTimeout('$("#response").fadeOut("slow")',4000);
}
else {
var datastr ='name=' + name + '&mail=' + mail + '&subject=' + subject + '&country=' + country;
$("#response").css("display", "block");
$("#response").html("<img src='http://infashionation.com/female/images/response.jpg'>");
$("#response").fadeIn("slow");
setTimeout("send('"+datastr+"')",2000);
}
return false;
});
The problem is it now doesnt submit regardless of whether box is checked or not.
Ive been searched for some information to help me with this for a while but no luck so thought I would ask here to see if anyone can help me.
There appears to be an extra exclamation point after the valid variable. I suggest also using a javascript debugger.
if (valid!='') {
You're missing a closing curly brace for your .ready function.
It doesn't look like you've closed the $(document).ready() function. You close the sendmail click function, but not the main function. I think the tail end of your code should look like this:
}
return false;
}); // close sendmail function
}); // close document.ready
If that happened because of copying it to SO, then disregard this, but if this is in your code, your browser will probably not do a thing and appear not to react to the JavaScript.
I've been working on this issue for a couple weeks now and have been unable to resolve it. The problem is only reported by a small subset of IE8 users. I have attempted to reproduce the problem by running a VM of windows xp, IE8 (same version users report), and synced browser security settings. Despite this, I am unable to reproduce the problem for myself. Reproducing it would be great, but ultimately all that matters is discovering the source of the problem.
The way the print function works is:
User presses a link on the page which triggers a javascript function.
The javascript performs some logic to get the content of a subsection of the page (based on which print link was clicked).
"exCanvas elements are set to display:none" because I found that they caused printing bugs.
4.The element is printed using a slightly modified version of "Print Element" found here: http://projects.erikzaadi.com/jQueryPlugins/jQuery.printElement/
The user then is prompted with a print dialogue from IE. When the user hits the "print" button IE hangs and can only be shutdown by ending the process. If the user hits "cancel" IE does not hang and the user can continue about their business.
The user is able to use the default print functionality to print the entire page without trouble. It is only when they used my javascript based print function that the browser hangs.
I've had the user run no-addon IE8, look in their windows event log, and disable some common problem features in IE8.
I'm really stumped as to where in the process this error may be occuring. It seems to point to my javascript but it stumps me that the error occurs after the browser print dialogue print button is pressed. I would expect the error to occur before the window.print() function is called on the focused iframe.
Any help would be greatly appreciated as this bug has given me quite a bit of frustration.
Thanks.
EDIT----------------------------------------
I use the standard jquery print library above with a slightly custom _getMarkup function as seen below:
function _getMarkup(element, opts) {
var $element = $(element);
var elementHtml = _getElementHTMLIncludingFormElements(element);
var html = new Array();
html.push('<html><head><title>' + opts["pageTitle"] + '</title>');
if (opts["overrideElementCSS"]) {
if (opts["overrideElementCSS"].length > 0) {
for (var x = 0; x < opts["overrideElementCSS"].length; x++) {
var current = opts["overrideElementCSS"][x];
if (typeof (current) == 'string')
html.push('<link type="text/css" rel="stylesheet" href="' + current + '" >');
else
html.push('<link type="text/css" rel="stylesheet" href="' + current["href"] + '" media="' + current["media"] + '" >');
}
}
}
else {
$("link", document).filter(function () {
return $(this).attr("rel").toLowerCase() == "stylesheet";
}).each(function () {
html.push('<link type="text/css" rel="stylesheet" href="' + $(this).attr("href") + '" media="' + $(this).attr('media') + '" >');
});
}
//Ensure that relative links work
html.push('<base href="' + _getBaseHref() + '" />');
html.push(hieviews.getPrintCSS($("head").html()));
html.push('</head><body style="' + opts["printBodyOptions"]["styleToAdd"] + '" class="' + opts["printBodyOptions"]["classNameToAdd"] + '">');
var contentStr = $('<div></div>');
$(contentStr).append($('#disclaimer').html());
$(contentStr).append($('#nav').html());
$(contentStr).append("<hr/><h3 class='table-header'>"+$(".title",$(element).parent().parent().children(":first")).text() +"</h3>");
$(contentStr).append('<div>' + elementHtml + '</div>');
var refTable = "";
var total = $(".show-tooltip-text, .hidden_report",contentStr).each(function(index){
if(index == 0){
refTable += "<h3>Reference Table</h3><table class=\"dataTable\" id=\"cite\"><thead><tr><th>ref</th><th>Content</th></tr></thead><tbody>";
}
//if($(this).is(":hidden")){
if($(this).css("display") != "block"){
$(this).parent().append("<sup>*ref: #"+index+"</sup>");
refTable += "<tr><td>"+index+"</td><td>"+$(this).html()+"</td></tr>";
}
if(index == total){
refTable += "</tbody></table>";
}
}).length;
$(contentStr).append(refTable);
html.push($(contentStr).html());
html.push('<script type="text/javascript">function printPage(){focus();window.print();' + ((!$.browser.opera && !opts["leaveOpen"] && opts["printMode"].toLowerCase() == 'popup') ? 'close();' : '') + '}<\/script>');
html.push('</body></html>');
return html.join('');
};