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
Related
I Have 3 input text in a form, that i would like to joini like this after pressing a button:
TextA-TextB TextC.
I also would like that will be positioniting on th first free line of the text area.
if for eaxmple ther is this situation:
2018-12345 25.00,
i would like that inserting the datas in the 3 text, will become like this:
2018-12345 25.00
TextA-TextB TextC
I imagine that i need javascript and calling the function with event onclick on the button, but i am not into javascript, because of that i am asking for your kind help.
Thanks for the fast answer.
I tried to combine a couple of codes that i found online, but i always get error 404 when I try it on fiddle:
<script>
function fillMessage() {
var annoTA1 = document.getElementById('annoTA') + " ";
var numTess1 = document.getElementById('numTess') + " ";
var impVer1 = document.getElementById('impVer1') + " ";
msg.value = annoTA1.value + numTess1.value + impVer1.value;
var targ = event.target || event.srcElement;
document.getElementById("message").value += targ.textContent || targ.innerText;
var Message= "";
function addText(text) {
Message+= text
}
document.getElementById("message").value = Message;
} </script>
and for the onclick event I used:
<button onclick="fillMessage()">Aggiungi Nuova Tessera</button>
the original fiddle is this:
http://jsfiddle.net/qmrt7z0w/
and plus I added
var Message= "";
function addText(text) {
Message+= text to test there before.
I solved with this script:
<script>
$('#btn').on('click', function (){
var insertText = $('#annoTA').val() + " ";
insertText += $('#numTess').val() + " ";
insertText += $('#impVer').val() + " ";
if(document.getElementById("annoTAG").value == ' ')
{
$('#annoTAG').val( $('#annoTAG').val() + insertText);
}
else
{
$('#annoTAG').val( $('#annoTAG').val() + '\n' + insertText);
}
});
</script>
And for the button i had to use:
<input type="button" value="Aggiungi Nuova Tessera" id="btn" />
Otherwise is not working...
Everything works good now, just that when I am inserting. The first row, it starts with a space. I tried to adding the backspace like this:
if(document.getElementById("annoTAG").value == ' ')
{
$('#annoTAG').val( $('#annoTAG').val() + '\b '+ insertText);
}
But did not works. Any suggestions?
Thanks
I am creating a BF4 weapon selector (tells you random weapons/attachments to equip), using the function below, and a link to refresh it (to run the function again), however when the link is clicked, it does not work (and there is no error in console)
Any ideas? JSFiddle
Just to clarify: the text appears, and as a link, however when you click the link (which runs javascript:CreateWeapons(), it does not work, and there is no error in JSFiddle, or in javascript console)
JS:
function Random(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
function CreateWeapons() {
document.getElementById('text').innerHTML = ('<a href="javascript:CreateWeapons();">' +
'Primary: ' + Primary +
'<br>' +
'Secondary: ' + Secondary +
'</a>');
}
var Primary = Random(["M16A4", "M16A3", "M416", "None"]);
var Secondary = Random(["None",".44 Deagle"])
CreateWeapons();
// BF4 weapon chooser (using random values)
HTML:
<div id="weapons">
<div id="text"></div>
</div>
If you want the Primary and Secondary weapons to change in each click, you have call Random method inside the CreateWeapons method.
Also it is not good way to use href to call js function, you can use onclick instead of that.
Here is the updated working code for you.
function Random(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
function CreateWeapons() {
var Primary = Random(["M16A4", "M16A3", "M416", "None"]);
var Secondary = Random(["None",".44 Deagle"]);
document.getElementById('text').innerHTML = ('<a href="#" onclick="CreateWeapons();return false;">' +
'Primary: ' + Primary +
'<br>' +
'Secondary: ' + Secondary +
'</a>');
}
CreateWeapons();
// BF4 weapon chooser (using random values)
It's better if you create an element and then use it's onclick event to call the function rather using the inline onclick event. Try this,
function Random(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
var aElement = document.createElement("a");
aElement.href="#";
function CreateWeapons() {
var Primary = Random(["M16A4", "M16A3", "M416", "None"]);
var Secondary = Random(["None",".44 Deagle"]);
aElement.innerHTML = ('Primary: ' + Primary + '<br />' + 'Secondary: ' + Secondary);
document.getElementById('text').appendChild(aElement);
return false;
}
aElement.onclick = CreateWeapons;
CreateWeapons();
jsFiddle
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.
on click event in node.js is not working but simple text input work.i want that when you click on buttons( in my case two buttons) the two different event happen but it does not work. these two different events are append DOM within page. one of the button have value 'X' and other one have 'O' and i want to just append DOM with button's value. How can i do that?
this is code--->
my script is-
$(function() {
var socket = io.connect(window.location.href);
socket.on('message:server', function(data) {
$("#messages").append(
'<li style="color:red">' +
data.message + ' - ' + 'received' + ' ' + new Date() +
'</li>'
);
});
$("#message_form").on('submit', function(event) {
event.preventDefault();
var $input = $('[name="message"]')
var message = $input.val();
if (message) {
socket.emit('message:client', {message: message});
}
$("#messages").append(
'<li style="color:green">' +
message + ' - ' + 'sent' + ' ' + new Date() +
'</li>'
);
$input.val('');
});
socket.on('error', function() {
console.error(arguments)
});
});
in Body tag-
<form id="message_form" method="post">
<input name="message" placeholder="Message to send" type="text"/>
<button type="submit">Submit</button>
</form>
here at bottom in place of form i want 2 buttons which can operate this with default given fix value.
What about creating two buttons in the DOM and calling .on('click', function(){}) instead of submit ?
Like :
<button id="value1">Send value 1</button>
<button id="value2">Send value 2</button>
Then you simply set the function on click event. I added comments to your code to show what you can remove :
$("#value1").on('click', function(event) {
event.preventDefault();
// var $input = $('[name="message"]');
// You don't need fix since you send "fixed" value
var message = "Value 1" // Or whatever you want instead of $input.val();
// if (message) {
// No need of condition since you set the value
socket.emit('message:client', {message: message});
// }
$("#messages").append(
'<li style="color:green">' +
message + ' - ' + 'sent' + ' ' + new Date() +
'</li>'
);
// $input.val('');
});
You simply do the same for your button 2.
For this example, you would call :
$('#value2').on('click', function(){
// Same as value with another message value
});
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.