I'm trying to prevent users from inputting and submitting single quotes ( ' ) into the textarea. below is what I have, but it isn't work.
<script>
function valtxtarea() {
var val = document.getElementById('textarea').value;
if ('\''.test(val)) {
alert('do not add single qoutes to your inputs!');
}
}
</script>
<form>
enter text below
<textarea>input contents here</textarea>
<input type="button" onclick="valtxtarea();" value="send">
</form>
You missed the id attribute as well as the regex isn't valid
function valtxtarea() {
var val = document.getElementById('textarea').value;
if (/\'/.test(val)) {
alert('do not add single qoutes to your inputs!');
}
}
<form>
enter text below
<textarea id="textarea"></textarea>
<input type="button" onclick="valtxtarea();" value="send">
</form>
Better yet, why not prevent them from even typing it?
<form>
enter text below
<textarea id='inputText' oninput="valtxtarea();"></textarea>
<input type="button" value="send">
</form>
<script>
var oldValue = "input contents here";
document.getElementById('inputText').value = oldValue;
function valtxtarea() {
var textArea = document.getElementById('inputText');
if (textArea.value.match(/.*\'.*/g)) {
textArea.value = oldValue;
} else {
oldValue = textArea.value;
}
}
</script>
With this every time they type a char it is check and if it contains a ' then it sets it back to the old value. You could easily expand it to include other characters you do not want to allow.
var val = document.getElementById('textarea').value;
There is no HTML element with the id textarea.
Do something like this:
<textarea id="textarea">input contents here</textarea>
Also you probably want to prevent form submission if there is a validation error, so put return false; in the if in valtxtarea() and put return valtxtarea() in the onclick.
Related
I am providing a form where the user shall enter an arithmetic calculation. Further down the result shall appear, once the user hits enter. It might just be a problem of syntax, but I couldn't find the mistake. Here is what I did so far:
<!DOCTYPE html>
<html>
<body>
<p>What do you want to calculate?</p>
<form method="post"><span>Type here:</span><input type="text" id="calc"></input>
</form>
<script>
num_field = document.getElementById("calc");
num_field.onsubmit=function ()
{
document.getElementById("display_result").innerHTML = num_field;
}
</script>
<p id="display_result"></p>
</body>
</html>
So, the user shall enter for instance "1+2". The result shall appear below.
Any idea where is my mistake?
Best regards
Here is how you can achieve that.
eval is the best way for doing that but eval is risky to use so make sure to sanitize the value of input before using eval.
I am using this regex /(^[-+/*0-9]+)/g to extract only numbers and few operators (-+/*) and doing eval on that value.
remove the <form> that is not required use keypress event listener and check for enter key. keycode of enter key is 13
num_field = document.getElementById("calc");
num_field.onkeypress = function(e) {
if(e.which==13)
{
var value = num_field.value.match(/(^[-+/*0-9]+)/g);
if(!value) return;
else value = value[0];
var res = eval(value);
document.getElementById("display_result").innerText = res;
}
}
<p>What do you want to calculate?</p>
<span>Type here:</span>
<input type="text" id="calc" />
<p id="display_result"></p>
You were nearly there, your code just needed a bit of tweaking - see below (comments in code as what I have done and why)
The following seems to be an alternate and safer way to do this without using eval (function taken from the second answer in this post):
<!DOCTYPE html>
<html>
<body>
<p>What do you want to calculate?</p>
<form method="post" id="form">
<span>Type here:</span>
<input type="text" id="calc"> <!-- inputs are self closing no need for closing tag -->
<input type="submit" value="submit"> <!-- added a submit button -->
</form>
<script>
form = document.getElementById("form");
num_field = document.getElementById("calc");
form.onsubmit = function() { // attach this event to the form
document.getElementById("display_result").innerHTML = evalAlternate(num_field.value); // add .value here to get the value of the textbox
return false; // return false so form is not actually submitted and you stay on same page (otherwise your display result will not be updated as the page is reloaded
}
function evalAlternate(fn) { // function safer alternate to eval taken from here: https://stackoverflow.com/questions/6479236/calculate-string-value-in-javascript-not-using-eval
fn = fn.replace(/ /g, "");
fn = fn.replace(/(\d+)\^(\d+)/g, "Math.pow($1, $2)");
return new Function('return ' + fn)();
}
</script>
<p id="display_result"></p>
</body>
</html>
see the below fiddle
https://jsfiddle.net/ponmudi/13y9edve/
num_field = document.getElementById("calc");
num_field.onkeydown = (event) => {
if (event.keyCode === 13) {
document.getElementById("display_result").innerHTML = eval(num_field.value);
return false;
}
}
This should work:
calc = document.getElementById("calc");
formula = document.getElementById("formula");
calc.addEventListener('click', function() {
document.getElementById("display_result").innerHTML = eval(formula.value);
});
<p>What do you want to calculate?</p>
<span>Type here:</span>
<input type="text" id="formula" />
<button id="calc" type="submit">calc</button>
<p id="display_result"></p>
eval() JavaScript Method
Try this:
var calculation_input = document.getElementById('calculation_input');
calculation_input.onkeydown = function(event) {
if (event.keyCode == 13) { // Enter key.
// Sanitize before using eval()
var calculation = calculation_input.value.replace(/[^-()\d/*+.]/g, '');
document.getElementById("display_result").innerHTML = eval(calculation);
}
}
<p>What do you want to calculate?</p>
<span>Type here:</span>
<input type="text" id="calculation_input" />
<p id="display_result"></p>
You don't need to submit the calculation in a form, you can just use native javascript to calculate the result. And don't forget to always sanitize before using eval :)
This is a form I have:
<h1>Word game!</h1>
<form id="joke-form">
<label>
Unscramble these letters to form a word:<Br>
<span class="scrambled">REYJUQ</span>
<br>
<input type="text" id = "userinput" size="10">
</label>
<button type="submit">Check</button>
</form>
And here is a jquery function I am running on it. My problem is that I don't know how to get the value that the user inputs in the textbox when they press submit. I am relatively new to jquery but have had no luck in researching this topic, including reading similar questions on this site.
<script>
$('#joke-form').on('submit', function(event) {
event.preventDefault();
var words = $('this input: first').val();
console.log(words);
});
if (words === "ANSWER") {
$('#result').text("You have the right answer");
}
else {
$('#result').text("Guess again!");
}
</script>
You have the code in the wrong place, and the selector you are using is incorrect for the input.
See this codepen on how this could work:
http://codepen.io/KempfCreative/pen/JGRzwm
$('#joke-form').on('submit', function(event) {
event.preventDefault();
var words = $('#joke-form #userinput').val();
console.log(words);
if (words === "ANSWER") {
$('#result').text("You have the right answer");
}
else {
$('#result').text("Guess again!");
}
});
Try:
var words = $('#userinput').val();
Your selector $('this input: first') is malformed. Since your input element has an id anyway, I would just select it by id instead. Also you will need to put your if else statement inside the submit function.
Here is a Live Demo of your code working in action:
$('#joke-form').on('submit', function(event) {
event.preventDefault();
var words = $('#userinput').val();
console.log(words);
if (words === "JQUERY") {
$('#result').text("You have the right answer");
} else {
$('#result').text("Guess again!");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Word game!</h1>
<form id="joke-form">
<label>
Unscramble these letters to form a word:
<Br>
<span class="scrambled">REYJUQ</span>
<br>
<input type="text" id="userinput" size="10">
</label>
<button type="submit">Check</button>
</form>
<span id="result"></span>
JSFiddle Version: https://jsfiddle.net/6pd5z9kv/1/
I see many anwsers already but here is what you've done wrong
your code
var words = $('this input: first').val();
fixed
var words = $(this).find("input:first").val();
//use 'this' seprately, then you start input:first with " and finished with '
hopefully it will work for you, and about html I dont know if its copy/pase issue but remove blank space with id and =
your code
id = "userinput"
fixed
id="userinput"
Rest is just fine :)
Cheers
I have a textbox that I would like to add text to by keyboard, as well as mix in some pre defined phrases from a drop down box. When I first come to the page there is no problem adding the phrases into the textbox, but once I type something in the button stops working
The HTML is:
<div class="tab-pane" id="message">
<textarea rows="4" cols="50" id="send_message" placeholder="Enter text ..."> </textarea>
Add Phrase
<label for=message_list>message_list</label><select id=message_list><option>Hi There.</option><option>How Are You?</option></select> </div>
My jquery is:
$('#message').on("click", "a", function(){
.......
..........
else if( $(this).is(":contains(Add Phrase)") ) {
$('#send_message').append($('#message_list').text());
}
});
How can I fix this?
Use val to set the value of textarea
And val to access the select value.
You were trying to use append on a form element.
$('#send_message').append($('#message_list').text());
supposed to be
$('#send_message').val($('#message_list').val());
Check Fiddle
$('#message').on("click", "a", function (e) {
e.preventDefault();
if ($(this).is(":contains(Add Phrase)")) {
var $message = $('#send_message')
previousText = $message.val();
var currText = previousText + ' ' + $('#message_list').val();
$('#send_message').val(currText);
}
});
<script type="text/javascript">
window.onload = init;
function init() { //wait for load and watch for click
var button = document.getElementById("searchbutton");
button.onclick = handleButtonClick;
}
function handleButtonClick(e) { //get user input and go to a new url
var textinput = document.getElementById("searchinput");
var searchterm = textinput.value;
window.location.assign("http://google.com/example/" + searchterm)
}
</script>
<form>
<input type="text" name="search" id="searchinput">
</form>
<input type="submit" value="Ara" id="searchbutton">
In this code block, it gets user input and go to a new url with user input.
if I move last line into form element it doesn't working.
But I'm using id to find elements.
you can specify the OnSubmit as explained in the below code fragment, and it will work.
<form method="GET" onsubmit="handleButtonClick(event)">
<input type="text" name="search" id="searchinput">
</form>
function handleButtonClick(e) {
var textinput = document.getElementById("searchinput");
var searchterm = textinput.value;
window.location.assign("http://google.com/example/" + searchterm)
return false;
}
I suspect that it is because your submit button is submitting the form.
Add e.preventDefault(); and return false; to your code.
function handleButtonClick(e) { //get user input and go to a new url
e.preventDefault();
var textinput = document.getElementById("searchinput");
var searchterm = textinput.value;
window.location.assign("http://google.com/example/" + searchterm)
return false;
}
This should stop the form from submitting cross browser.
Instead of
<input type="submit" value="Ara" id="searchbutton">
use this (MDN docu)
<button type="button" id="searchbutton">Ara</button>
Your button works as a form submit button, so instead of just executing your JavaScript, it also tries to submit the form, which points back to the script itself. By using <button type="button"> you define a mere button without any submitting functionality.
Besides: If you don't need the surrounding <form> element, why not drop it out of the code?
I'm using a script to return what the user types on an inputbox without www.
I want the modification to work in the inputbox itself. Is this possible?
Like for example the user types: www.example.com and when he presses GO www. disappears from what he typed and then the text is highlighted (selected).
<input type="text" id="url" />
<input type="button" id="submit" value="Go!" />
<div id="output"></div>
<script>
$("#submit").click(
function() {
var url = $("#url").val();
if(url.match(/^www\./))
{
url = url.substring(4);
}
$("#output").html(url);
}
);
</script>
Yes, $("#url").val(url);
http://jsfiddle.net/hk5zx/
Update:
He wants the text selected too!
$("#url").val(url).focus().select();
http://jsfiddle.net/hk5zx/1/
$("#submit").click(
function() {
var url = $("#url"),
val = url.val();
if(val.match(/^www\./))
{
val = val.substring(4);
url.val(val);
}
$("#output").html(val);
}
);
Yes, set the value through jQuery with $("#url").attr("value", url);.