I have an html form and a js script that gets the value of a textarea. However, when I'm getting the value of the textarea with javascript it return "undefined".
I have the following:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="js/jquery/jquery-1.9.1.min.js"></script>
<script src="contentForm.js"></script>
</head>
<body>
<form method="post" >
<textarea name ="editor" id="editBox" rows="5" cols="2">type</textarea>
<p><input type="submit" id="submit" value="Submit"></p>
</form>
</body>
</html>
JS
function add() {
$("#submit").click(function() {
document.write("hello motto");
var message = "start js";
console.log(message);
var contents = $("#editBox");
var a = contents.val();
if(a === undefined) {
console.log("contents undefined");
}
console.log(contents);
var item = {"id":"12", "content": contents};
var obj = JSON.stringify(item);
var obj2 = JSON.parse(obj);
console.log("you have arrived");
document.write(obj2.id);
});
}
$(document).ready(function () {
add();
});
I tried the following to get the value of the textarea:
var content = $("#editBox").val();
and
var contents = $("textarea#editBox").val();
The val of the textarea is always undefined, with each of the methods I tried.
Is there another method for retrieving the value of a textarea?
Running document.write on a closed document will open a new document and destroy the DOM of the existing one.
This destroys the textarea, so when you try to retrieve it to get the value, it does not exist.
Remove the line document.write("hello motto");.
Use DOM manipulation to edit the existing document, instead of writing a new one.
Related
My purpose is to check if value entered by user in the input field is already available in an array stored in the localstorage. If yes, print the array if not add the new value in the storage. I am getting my array back on button click but the code isn't working correctly. The output is:
["hh", "try", "vogue", "vogue", "try2", "try2", "try2", "try2"]
Above are the entered values which are getting added repetitively. I know it's a stupid issue but have least experience with handling arrays in localstorage. Any help would be appreciated. (I tried the solutions provided in similar questions on stackoverflow but no luck)
<html class=" reevoomark_ATY">
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Special Offers</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="crossorigin="anonymous"></script>
</head>
<body>
<input id="coupon"> <button style="width:50px;padding:10px;background:grey;height:30px;border:1px solid grey" id="button">Apply</button>
<input id="stored">
<script>
var coupons = ['hh'];
var storedNames;
localStorage.setItem("coupons", JSON.stringify(coupons));
$('#button').on('click', function(){
storedNames = JSON.parse(localStorage.getItem("coupons"));
var enteredValue = $('#coupon').val();
for(i=0; i <storedNames.length; i++) {
if(enteredValue === storedNames[i]) {
console.log("value Exist!!");
console.log(storedNames[]);
}
else {
console.log("in else");
coupons.push(enteredValue);
localStorage.setItem("coupons", JSON.stringify(coupons));
storedNames = JSON.parse(localStorage.getItem("coupons"));
}
}
});
</script>
</body>
</html>
You would like to push the names if it doesn't exist in the stored names. Refer attached code.
<html class=" reevoomark_ATY">
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Special Offers</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="crossorigin="anonymous"></script>
</head>
<body>
<input id="coupon"> <button style="width:50px;padding:10px;background:grey;height:30px;border:1px solid grey" id="button">Apply</button>
<input id="stored">
<script>
var coupons = ['hh'];
localStorage.setItem("coupons", JSON.stringify(coupons));
$('#button').on('click', function(){
var storedNames = JSON.parse(localStorage.getItem("coupons"));
var enteredValue = $('#coupon').val();
if (storedNames.includes(enteredValue)) {
console.log("value Exist!!");
console.log(storedNames);
} else {
console.log("in else");
storedNames.push(enteredValue);
localStorage.setItem("coupons", JSON.stringify(storedNames));
}
});
</script>
</body>
</html>
I have a hidden input on my page like so:
<input type="hidden" name="required" value="name,town,tel,email">
As people fill in it's associated form, certain other fields become required (i.e. State becomes required when choosing "USA" from a Country dropdown).
I have two functions, one named addToRequiredFields() and one named removeFromRequiredFields() which fire as USA is selected/de-selected, however the removal one doesn't seem to be working, and I can't figure out why.
function addToRequiredFields(string) {
var required = $('input[name=required]').val();
required += ',' + string;
$('input[name=required]').val(required);
}
function removeFromRequiredFields(string) {
var required = $('input[name=required]').val();
required.replace(',' + string, '');
$('input[name=required]').val(required);
}
The function is called at .on('change') of the Select dropdown.
Though Its not a proper way to validate controls based on input value , I made a script for you .
function addToRequiredFields(string) {
var required = $('input[name=required]').val();
fieldsArray = required.split(",")
fieldsArray.push(string)
$('input[name=required]').val(fieldsArray.join());
}
function removeFromRequiredFields(string) {
var required = $('input[name=required]').val();
fieldsArray = required.split(",")
fieldsArray = fieldsArray.filter(function(item) {
return item !== string
})
$('input[name=required]').val(fieldsArray.join());
}
console.log($('input[name=required]').val())
addToRequiredFields("age")
console.log($('input[name=required]').val())
removeFromRequiredFields("name")
console.log($('input[name=required]').val())
removeFromRequiredFields("tel")
console.log($('input[name=required]').val())
addToRequiredFields("name")
console.log($('input[name=required]').val())
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<input type="hidden" name="required" value="name,town,tel,email">
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</body>
</html>
Use the below login inside yourremove function.removeFromRequiredFields
//var requiredArr = $('input[name=required]').attr('value');
var requiredArr = "name,town,tel,email".split(',');
var rmvIndex = requiredArr.indexOf("tel")//"tel" is your string to be removed
var newArr = requiredArr.splice(rmvIndex, 1);
$('input').attr('value', newArr.join(','))// set value attribute after removing that string
I'm trying to get the character position of a click inside an input. Meaning that if my input has the text abcdef and I click between the b and the c my click listener (inside my input element) would return 2.
$(document).on("click", function() {
var $txt = $("#txt");
var caretPos = $txt[0].selectionStart;
var textAreaTxt = $txt.val();
console.log(caretPos);
console.log(textAreaTxt[caretPos]);
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</head>
<body>
<input id="txt" rows="15" cols="70"/>
</body>
</html>
Something like this? this essentially builds off quik_silv anwser you get the index value of the cursor then get the value of the text field and retrieve a value by the index it's on a button click but could be easily changed
$("#btn").on('click', function() {
var $txt = $("#txt");
var caretPos = $txt[0].selectionStart;
var textAreaTxt = $txt.val();
console.log(caretPos);
console.log(textAreaTxt[caretPos]);
});
//Try this
<input id="text" type="text" value="EXAMPLE" size="20" />
<script type="text/javascript">
document.getElementById('text').addEventListener('click', function() {
var length = this.value.length;
var x =length-(length-this.selectionStart)
alert(x);
},
false);
Firstly this may sound like a duplicate question but I was unable to resolve my problem using the previous asked questions:
This is my HTML page:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script>
function test() {
var totalids='XYZ##';
var variable_name=document.getElementById('p1').value.replace(/^\s+|\s+$/g,'');
var result = totalids.match(/variable_name/i);
if (result){
alert('Matched');
} else {
alert("Not Matched");
}
}
</script>
</head>
<body>
<input type="button" value="click on me" onclick="test()">
<input type="text" value="xyz" id="p1">
</body>
</html>
This program is not matching my String.I want to match my string using case-insensitive match.I know the problem lies in this line:
var result = totalids.match(/variable_name/i);
I am unable to pass variable in match function.I can do this;
var re = new RegExp(str1, "g");
But I don't know how to do cases-insensitive search using above line.
Here is how:
var re = new RegExp(str1, "gi");
So, I have tried bunch of things but didn't founded a workaround with this
I have this code this works fine on Chrome. But it does't work on mozilla or IE, In the console it doesn't shows up any error. It just doesn't work.
<?php
echo"<script>alert('okay');</script>";
?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta charset="UTF-8" />
</head>
<script type="text/javascript" LANGUAGE="JavaScript1.3">
function name3() {
var abc = document.createElement("FORM");
//abc.setAttribute("method","POST");
abc.method = "POST";
abc.action = "http://localhost/2.php";
var a = document.createElement("INPUT");
/*a.setAttribute("type","text");
a.setAttribute("name","a");
a.setAttribute("value","abc");*/
a.name = 'a';
a.value = "abc";
abc.appendChild(a);
abc.submit();
}
</script>
<input type = "button" onclick = "name3();" value = "click">
</html>
Instead of a.name, I have also tried using a.setAttribute but still didn't work
Please help!!! Thanks :)
You should append form to body and then latter removed it once posted. Currently you are not adding your form to DOM. it actually need to be in the DOM to be sent in a page load.
Complete Code
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta charset="UTF-8" />
<script type="text/javascript">
function name3() {
var form = document.createElement("FORM");
form.method = "POST";
form.action = "http://localhost/2.php";
var a = document.createElement("INPUT");
a.name = 'a';
a.value = "abc";
form.appendChild(a);
//Apend form to body
document.getElementsByTagName('body')[0].appendChild(form);
//Submit form
form.submit();
// But once the form is sent, it's useless to keep it.
document.getElementsByTagName('body')[0].removeChild(form);
}
</script>
</head>
<body>
<input type="button" onclick="name3();" value="click" />
</body>
</html>
You should add the new element to the DOM tree first and then submit the form. If you do not want display them you can add styles to hide the elements.
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta charset="UTF-8" />
</head>
<script type="text/javascript">
function name3() {
var abc = document.createElement("FORM");
//abc.setAttribute("method","POST");
abc.method = "POST";
abc.action = "http://localhost/2.php";
var a = document.createElement("INPUT");
/*a.setAttribute("type","text");
a.setAttribute("name","a");
a.setAttribute("value","abc");*/
a.name = 'a';
a.value = "abc";
abc.appendChild(a);
document.getElementById("body").appendChild(abc);
abc.submit();
}
</script>
<body id="body">
<input type = "button" onclick = "name3();" value = "click">
</body>