Call JS function after paste keyboard shortcut? - javascript

I'm trying to write a simple script that will take a list of urls that I need to save, append them to an array, and then spit that array back out in a div. The problem I'm having is that I am using ".onKeyUp" to call the function. It works, but when I use ctrl + v to paste, the function gets called twice. Once when you release the letter v and once when you release control. How can I fix it so that it will only call the function once when I'm using the keyboard shortcut? Here is my code:
<script type="text/javascript">
var arr = new Array();
function procession() {
var urlin = document.getElementById('url').value;
var smacky = "<br/> the url is: " + urlin + "<br/> the url is: www." + urlin;
arr.push(smacky);
document.getElementById('list').innerHTML = arr;
}
</script>
<form>
<input onkeyup="procession();" type="text" size="50" id="url"/>
</form>
<div id="list"></div>
Important Note: It's a long story, but I can't use jQuery for this script. Is there a way to do it in just pure javascript?

Pass in event to your onKeyUp, if the key is a ctrl, return false. This will only register one keyup event for shortcuts now:
<input onkeyup="procession(event);" type="text" size="50" id="url"/>
JS:
function procession(e) {
//if ctrl key, return false
if (e.which == 17) return false;
//do stuff
var urlin = document.getElementById('url').value;
var smacky = "<br/> the url is: " + urlin + "<br/> the url is: www." + urlin;
arr.push(smacky);
document.getElementById('list').innerHTML = arr;
}
It's a little hack-ish, but it should get the job done.

Here:
$(document).on("paste", function(event) {
alert("paste!");
});

Related

Return a value created in an event handler inside a function from the same function

I have an input box and a go button. When the user clicks the go button I want to compare the inserted value with another value. I am trying to acquire the input value inside a function like so
function getInput(){
var entry ='';
$('button.go').on('click',function(){
var entry = $(this).siblings('.input').val();
//return entry
})
return entry
}
Basically I want to return the var entry that has an input value, so I could compare the values later in the code
var input = getInput() // this should have input value
is input > othervalue
I call getInput inside document.ready()
You are doing everything right . There are some scope related issues that is not helping you to get the expected result . My suggestion would be to define othervalue variable as global and check it inside the function like this
function getInput(){
$('button.go').on('click',function(){
var entry = $(this).siblings('.input').val();
if(entry>othervalue) //your code
});
}
I am not sure why you are binding dynamic click event inside a function . If there is nothing else you need to do here except this part, then wrap this piece of code inside document.ready.
I would suggest to declare your var entry =''; globally and assign it before comparing.
var entry="";
$('button.go').on('click',function(){
entry = $(this).siblings('.input').val();
});
//do the comparing..
You should do the comparing, after delegating the click function, inside the function.
var entry = "";
$('button.go').on('click', function(){
var entry = $(this).prev('.input').val();
if (entry < x)
// Do something
});
It remains unclear to me what you want to accomplish.
I made some code that might be somewhere near what you want.
jQuery().ready(function()
{
var startValue = $('input[name="the_input"]').val();
$('form').submit(function()
{
var currentValue = $('input[name="the_input"]').val();
$('body').append('<br />' + startValue + ' - ' + currentValue + ' = ' + (startValue - currentValue));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="#" method="post">
<input type="text" value="10" name="the_input" /><br />
<input type="submit" value="go!" />
</form>

Textarea value remain the same after submitting a form

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

Dynamically building a button with an onClick

I am dynamically building a button in JavaScript, this will include an onClick event. The onClick event needs to focus a field which is stored in a variable.
I couldn't find a way of using the field variable itself, so instead decided to try using the field.selector property from the JQuery object, this WILL contain " ".
Here is a code snippet of the construction as it stands.
InvalidField.prototype.getMessageStructure = function(){
var structure = '<div class="invalidMessage"><span>' + this._message + '</span>
<button class="inputButton"
Value="Go To Field"
onclick=\'goToFieldFromAlert($(\'' + this._field.selector + '\'))\'
/>
</div>';
return structure;
};
This is outputting:
<button class="inputButton"
value="Go To Field"
onclick="goToFieldFromAlert($(" input[name="applicant.email" ]'))'="">
</button>
As you can see, the quotations will not be out put correctly and so break on click.
Can anyone foresee a better way of performing this function, or correcting the quotations? I see from this SO Answer that the DOM doesn't respect the quotations which is what is currently causing me the issue.
Kind Regards.
As I mentioned in comment, avoid using onclick at all. jQuery event handlers are far more flexible (and support multiple event handlers).
1) Inject the fieldname (only, not the jQuery selector) into a data- attribute:
InvalidField.prototype.getMessageStructure = function(){
var structure = '<div class="invalidMessage"><span>' + this._message + '</span>
<button class="inputButton"
value="Go To Field" data-field="' + this._field.name + '"/>
</div>';
return structure;
};
2) Use a delegated event handler to get all clicks on inputButtons with less overhead. Extract the field name and do the jQuery where it belongs:
$(document).on('click', '.inputButton', function() {
var $button = $(this);
var field = $button.data('field');
goToFieldFromAlert('input[name="' + field + '"]');
});
You should create element using jQuery. This is much cleaner and error free approach
An example with your code
InvalidField.prototype.getMessageStructure = function(){
var structure =
$('<div></div>').append(
$('<span></span>').text(this._message)
);
structure.append(
$('<button></button>')
.addClass('inputButton')
.text("Go To Field")
.click(function(){
goToFieldFromAlert($(this._field.selector));
})
);
return structure;
};
The following example will dynamically add buttons:
hello.forEach( function(result) {
var card = document.createElement("input");
card.type = "button";
card.onclick = function() {
newcard( result );
}
card.value = value; // some value
card.style.backgroundColor="#5ABC7B";
document.body.appendChild(card);
});

Change form input value with javascript

I am trying to change the input value of a hidden form to update the score of a game in my database.
I have this form code on a php page that displays and plays the game.
<form id ="recordForm" method="POST" action="updatePHP.php">
<input type='hidden' name="record" id='record' value='' />
</form>
And am trying to change the value of the hidden input field with this javascript. This is in the separate javascript file that is controlling the game.
function postPHP(newRecord){
alert("POST TO PHP"); //test to make sure I am calling this function
alert (newRecord); //alerts the correct value
var elem = document.getElementById('record');
elem.value = 12;
// document.getElementById('record').value = newRecord;
// document.getElementById('recordForm').submit();
};
There are a lot of topics on this subject but I am just not able to figure out what I am doing wrong. Any suggestions?
you should try
elem.value = newRecord;
Your JS function should work like this, i tested, more less what you already have. I remove the alerts since you don't need them anymore and leave what you have commented. This means your JS function isn't the problem.
function postPHP(newRecord)
{
document.getElementById('record').value = newRecord;
document.getElementById('recordForm').submit();
};
Don't forget to sent the parameter when calling the JS function, i did it with a button
<button onClick="postPHP('14')">Change</button>
since your JS function is in a separate file don't forget to include it in the File where you call the function
<head>
<script type="text/javascript" src="PATH/exampleName.js"></script>
</head>
Replace the src of the above tag to your needs
And last but not least check your updatePHP.php with a call to the method print_r
print_r($_POST);
All that should make the trick
Thank you for all your suggestions! This was my first question ever, I will look at all of them and see if I can get it working.
This is where I am calling postPHP:
function checkScore(score, record) {
alert('Score= ' + score);
alert ('Record= '+ record);
if(score < record || record === 0){
alert ("NEW RECORD"); //this alert is displayed when needed
postPHP(score);
}
};
and checkScore was called when the user moved a target crate back to the beginning spot and the following statement was executed
if (this.hasWon()) {
var finalScore = this.getScore();
var record = this.getRecord();
checkScore(finalScore, record);
return ret; //moving not allowed
}
there are some access methods used there.
//access methods
Board.prototype.hasWon = function() {
return state === 1;
};
Board.prototype.getScore = function() {
return score;
};
Board.prototype.getWt = function(r, c) {
return b[r][c];
};
Board.prototype.getData = function() {
return {"bobR": bobR, "bobC": bobC, "bobDir": bobDir,
"tgtR": tgtR, "tgtC": tgtC,
"startC": startC, "n": n};
};
Board.prototype.getRecord = function(){
var s = "" + window.location;
var ampIdx = "" + s.indexOf("&");
ampIdx = parseInt(ampIdx);
ampIdx = ampIdx + 7;
var record = "" + s.substring(ampIdx);
//alert("Puzzle Record= " + record);
record = parseInt(record);
return record;
}
;
I do have the javascript included. I do call it once in the body of the HTML, for some reason it doesn't display the game correctly when included in the head.
Again, thank you for the help! I will let you know what I get to work!
This is what I got to work.
function postPHP(newRecord, seed) {
alert("POST TO PHP");
var inner = "<input type='hidden' name='record' id='record' value=" + newRecord + " >"+
"<input type='hidden' name='seed' id='seed' value=" + seed + " >";
document.getElementById('recordForm').innerHTML = inner;
document.getElementById('recordForm').submit();
};
Thanks again for all the help, I just don't know why the first method wasn't working. This is my first attempts at PHP and javascript.

can't get the second javascript function to work?

i can't get second javascript function to work.
when i click 'Send Mail' button it should call the second function and pass it these two values.
the href line (second last line in first function) is not rendered correctly.
<script>
function getvals(first,second) {
alert(''+first+'');
alert(''+second+'');
mywindow=window.open('','Send Mail','height=200,width=400');
mywindow.document.write("<FORM NAME='test'>");
mywindow.document.write("<table align='center'><tr><td>User/Group: </td><td><input type='text' id='newfirst' name='iuser'></td></tr>");
mywindow.document.test.iuser.value = ''+first+'';
mywindow.document.write("<tr><td>Issue Key: </td><td><input type='text' id='newsecond' name='ikey'></td></tr>");
mywindow.document.test.ikey.value = ''+second+'';
mywindow.document.write("<tr><td><a href='javascript:popitup(document.getElementById('newuser').value,document.getElementById('newkey').value);'>Send Mail</a></td></tr></table>");
mywindow.document.write("</FORM>");
}
function popitup(user,key) {
alert(''+user+'');
alert(''+key+'');
var url = 'http:\/\/localhost:8080/plugins/servlet/mailservlet?receiver=' + user + '&issue=' + key;
newwindow=window.open(url,'name','height=400,width=400');
if (window.focus) {newwindow.focus()}
}
</script>
The function popitup will not be called as it is written in the parent window, not in the window opened by window.open. Try window.opener in your function call.
Nested quotes problem, you sould correctly escape it:
mywindow.document.write("<tr><td><a href='javascript:popitup(document.getElementById(\"newuser\").value,document.getElementById(\"newkey\").value);'>Send Mail</a></td></tr></table>");
See it working
function getvals(first,second) {
alert(''+first+'');
alert(''+second+'');
mywindow=window.open('','Send Mail','height=200,width=400');
mywindow.document.write("<FORM NAME='test'>");
mywindow.document.write("<table align='center'><tr><td>User/Group: </td><td><input type='text' id='newfirst' name='iuser'></td></tr>");
mywindow.document.test.iuser.value = ''+first+'';
mywindow.document.write("<tr><td>Issue Key: </td><td><input type='text' id='newsecond' name='ikey'></td></tr>");
mywindow.document.test.ikey.value = ''+second+'';
mywindow.document.write("<tr><td>Send Mail</td></tr></table>");
mywindow.document.write("</FORM>");
}
function popitup(user,key) {
alert(''+user+'');
alert(''+key+'');
var url = 'http:\/\/localhost:8080/plugins/servlet/mailservlet?receiver=' + user + '&issue=' + key;
newwindow=window.open(url,'name','height=400,width=400');
if (window.focus) {newwindow.focus()}
}
Issues fixed:
1) Escaping problem in window.open
2) function call should be opener.popitup
3) Id names for user and key were incorrect.
please dont do it like this (document write)
use appendChild, and append the onclick-handler there

Categories

Resources