dynamically adding form elements in javascript in IE/Mozilla - javascript

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>

Related

How can I access a variable in Jquery and use its value in another external .js file ? The variable is $generatedP

I need to access in a different .js file the value inside $generatedP and display it
$(document).ready(function() {
var $buttonValue = $(".value_generate");
var $divValue = $(".generated_value");
var $generatedP = $(".generated_p");
var $valueInput2 = $(".value_input_2");
var $submitPages2 = $(".submit_pages_2");
function valueGenerator(value) {
var valueString="";
var lettersNumbers = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for(var i = 0; i < value; i++)
valueString += lettersNumbers.charAt(Math.floor(Math.random()* lettersNumbers.length));
return valueString;
}//generate string
$buttonValue.click(function generate() {
var $key = valueGenerator(12);
$generatedP.html($key);//display generated string
});
$submitPages2.click(function() {
if($valueInput2.val() == $generatedP.text() ){
alert("you are logged in website");
} else {
alert("please check again the value");
return false;
}//check value if true/false
});
I am new to jquery
You have a few options.
Create a namespace inside the jQuery object:
$.myGlobalNamespace = {};
$.myGlobalNamespace.generatedPvalue = "something";
Define an object at the window level:
window.myGlobalNamespace = {};
window.myGlobalNamespace.generatedPvalue = "something";
Just be sure to use a sensible name for the namespace object.
You can improve the behavior doing client-side checking with localStorage, or you can simply use sessionStorage. Variable $generatedP will be available in page1 and page2. Hope it helps!
PAGE 1:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<script type = "text/javascript">
$(document).ready(function(){
var $generatedP = "27.23.10";
sessionStorage.setItem('myVar', $generatedP);
window.location.href = "page2.html";
});
</script>
</body>
</html>
PAGE 2: to access the variable just use the getItem method and that is all.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
var data = sessionStorage.getItem('myVar');
alert(data);
</script>
</body>
</html>

Get click character position inside an input (not coordinate)

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);

Passing javascript variable from one html page to another page

Hello All i started working on html recently,but iam struck in this situation where i want to send a value from one html page to the next html page just like,how websites shows our name after sign up success.Here i have written two html pages with,
pageOne.html
<!DOCTYPE html>
<head>
<title>
Home
</title>
<meta charset="UTF-8">
</head>
<style>
.myP{
color: lightgreen;}
</style>
<body>
<p id="p1" class="myP" onclick="myFun()">DataSend</p>
</body>
<script>
function myFun(){
document.getElementById("p1").style.color = "blue";
var textprevi=document.getElementById("p1").innerHTML;
localStorage.setItem("message", textprevi);
window.open("pageTwo.html","_self");
}
</script>
</html>
and my second
pageTwo.html
<!DOCTYPE html>
<html>
<body onload="fun">
<input type="text" id="tBox">
</body>
<script>
function fun()
{
document.getElementById("tBox").innerHTML = localStorage.getItem("message");
}
</script>
</html>
But when i tried the above solution,the element with id = "tBox" was empty but i wanted it to be filled with value = "DataSend" which is from pageOne.html.
Please help me with the promblem.
Thanks in advance.
The problem is with this line
document.getElementById("tBox").innerHTML = localStorage.getItem("message");
Here tBox is a an input element. So you have to use value instead of innerHTML
document.getElementById("tBox").value= localStorage.getItem("message");
You can do it using querystring parameters
In page one:
function myFun(){
document.getElementById("p1").style.color = "blue";
var textprevi=document.getElementById("p1").innerHTML;
window.open("pageTwo.html?data=" + textprevi,"_self");
}
In page 2
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var data = getParameterByName('data');
You made two mistakes in pageTwo.html.
<!DOCTYPE html>
<html>
<body onload="fun()"><!-- You didn't invoke the function here -->
<input type="text" id="tBox">
</body>
<script>
function fun()
{
document.getElementById("tBox").value = localStorage.getItem("message"); // You need to set the value for input fields, not innerHTML.
}
</script>
</html>
These changes should make your code work.

Getting value of textarea returns undefined

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.

Creating paragraphs based on user input

I'm having trouble, grabbing the user input, and having the onclick operator create additional paragraphs with each click.
Here is my HTML code.
<!DOCTYPE html>
<html lang='en'>
<head>
<title>Add Paragraph </title>
<meta charset='utf-8' >
<script src="../js/addPara.js" type="text/javascript"></script>
</head>
<body>
<div>
<input type='text' id='userParagraph' size='20'>
</div>
<div id="par">
<button id='heading'> Add your paragraph</button>
</div>
</body>
</html>
Here is Javascript code:
window.onload = function() {
document.getElementById("addheading").onclick = pCreate;
};
function pCreate() {
var userPar= document.createElement("p");
var parNew = document.getElementById('userParagraph').value;
userPar.innerHTML = par;
var area = document.getElementById("par");
area.appendChild(userPar);
}
userPar.innerHTML = par;
should be
userPar.innerHTML = parNew;
In your code:
> window.onload = function() {
> document.getElementById("addheading").onclick = pCreate;
> };
Where it is possible (perhaps likely) that an element doesn't exist, best to check before calling methods:
var addButton = document.getElementById("addheading");
if (addButton) {
addButton.onclick = pCreate;
}
Also, there is no element with id "addheading", there is a button with id "heading" though.
> function pCreate() {
> var userPar= document.createElement("p");
> var parNew = document.getElementById('userParagraph').value;
> userPar.innerHTML = par;
I think you mean:
userPar.innerHTML = parNew;
if you don't want users inserting random HTML into your page (perhaps you do), you can treat the input as text:
userPar.appendChild(document.createTextNode(parNew));
.
> var area = document.getElementById("par");
> area.appendChild(userPar);
> }
Your variable names and element ids don't make a lot of sense, you might wish to name them after the data or function they represent.
I did it and it worked.
<html lang='en'>
<head>
<title>Add Paragraph </title>
<meta charset='utf-8' >
<script>
window.onload = function() {
document.getElementById("heading").onclick = pCreate;
}
function pCreate() {
var userPar= document.createElement("p");
var parNew = document.getElementById('userParagraph').value;
userPar.innerHTML = parNew;
var area = document.getElementById("par");
area.appendChild(userPar);
}
</script>
</head>
<body>
<div>
<input type='text' id='userParagraph' size='20'>
</div>
<div id="par">
<button id='heading'> Add your paragraph</button>
</div>
</body>
</html>```

Categories

Resources