Passing a form variable from HTML to Javascript, but with quotes - javascript

I'm trying to pass an email address from an HTML form into a javascript snippet to pass to another program.
Form input:
<input name="email" placeholder="Enter Email Address Here" type="email" required="required" id="email_input">
Here's an example of what I'm looking for, note the quotes. In order for the email to pass, it must be within quotes.
<script type="text/javascript">
test({
email: "example#example.com",
});
</script>
Here's what I've tried:
<script type="text/javascript">
test({
email: "document.getElementById("email_input");",
});
</script>
If I'm using a static value like example#example.com, everything works as expected. I'm not able to figure out how to pass the value from the email input field to the "email:" javascript and have it pass though.
Heres what I need: What I have in there document.getElementById("email_input"); is not working, what should this be?
I'm know I'm missing something simple here, just not sure what.
Thanks in advance!

If you're just trying to pass the value of the email input using that test object, this is what you need.
var emailString = document.getElementById("email_input").value;
test({
email: emailString,
});
</script>
You want to grab the value of the input first, and then pass it as a string (assuming you need a string from your first example)

There is two way to get a string from an other typeof element (DOM element, Number, Array, ...) :
<script type="text/javascript">
var elmt = document.getElementById("email_input");
var str1 = elmt.toString();
var str2 = elmt + "";
// alert(str1); and alert(str2) will pop the same result : a string of elmt
</script>
so if you want the entire input as a string you should do :
<script type="text/javascript">
test({
email: document.getElementById("email_input") + ''
});
</script>
if you just want the input value as a string (so the email) you should do :
<script type="text/javascript">
test({
email: document.getElementById("email_input").value + ''
});
</script>
and if you really need to add quotes to a string you also can do :
<script type="text/javascript">
var str= "this is my string";
var withquote= ' " ' + str + ' " ';
//both of the var return a string but one will have a quote and the other won't
alert(str); // pop: this is my string
alert(withquote); // pop "this is my string"
</script>
So in your case :
if you want the entire input as a string with quotes you should do :
<script type="text/javascript">
test({
email: ' " ' + document.getElementById("email_input") + ' " '
});
</script>
if you just want the input value as a string (so the email) with quotes you should do :
<script type="text/javascript">
test({
email: ' " ' + document.getElementById("email_input").value + ' " '
});
</script>
hope I've made myself clear
Feel free to ask if I'm not
have a good one

Related

How to make a space when concatenating strings

I have written some code that works fine but I am trying to make a space between the strings.
The code I have is:
<html>
<head>
<title> Concatenating Strings </title>
</head>
<body>
<script type = "text/javascript">
var greetingString = "Hello";
var myName = prompt ("Please enter your name","");
var concatString;
document.write(greetingString + "" + myName + "<br>");
concatString = greetingString + "" + myName;
document.write(concatString);
</script>
</body>
</html>
At the moment the script shows HelloMichael, I am wanting it to show Hello Michael. Can someone please advise me on how I can do that?
To insert a space character, simply insert a space character. For example:
greetingString + " " + myName
There's no space in your current output, because "" doesn't have a space in it.
put a space between hello and michael like this:
concatString = greetingString + " " + myName; //notice the space in the string
concatString = greetingString + " " + myName;
Simply change your "" to " ", the second has a space in it.

Jquery find with multiple matches

I'm using Jquery to find the users email in my site, but I don't know how can I find a email for users with the same name.
Using this code, my variable return just one value for string.
var mail = $("#dat").contents().find("td:contains('" + name + "')" ).siblings("td").eq(1).text();
How can I get all strings that match in this find event?
Thanks!
EDIT: My code don't have any HTML markup for data, I'm using Google Spreadsheet to get the values.
Imagine there is one table with:
<tr><td>Name 1</td><td>mail1</td></tr>
<tr><td>Name 2</td><td>mail2</td></tr>
<tr><td>Name 1</td><td>mail3</td></tr>
If I use find containing "Name 1", my variable should return mail1, mail3.
To get the second column of all matching rows, use nth-child.
To get all values in an array, you can use map() and get()
var name = 'Name 1';
var mail = $("#dat").contents()
.find("td:contains('" + name + "')" )
.siblings("td:nth-child(2)")
.map(function() {
return $(this).text();
}).get()
document.body.innerHTML = '<pre>' + JSON.stringify(mail, 0, 4) + '</pre>';
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="dat">
<tr><td>Name 1</td><td>mail1</td></tr>
<tr><td>Name 2</td><td>mail2</td></tr>
<tr><td>Name 1</td><td>mail3</td></tr>
</table>
The query for find could be more specific as well, that way using siblings wouldn't be neccessary
var mail = $("#dat").contents()
.find("tr:has(td:contains('" + name + "')) td:nth-child(2)" )
.map(function() {
return $(this).text();
}).get()
You should change you code a little, to:
mail = $("#dat").contents().find("td:contains('" + name + "')" ).next().text();
Check demo - Fiddle

Display form input in same page

I am working on a simple form demo and i would like the input to display in a below the form. Currently i have it populating in the console. How do i may it display in the div when i click the submit button?
My code:
$(document).ready(function() {
$('.submitForm').on('click',function(event){
event.preventDefault();
$('#firstName').val();
$('#lastName').val();
$('#phoneNumber').val();
$('#address').val();
console.log($('#firstName').val());
console.log($('#lastName').val());
console.log($('#phoneNumber').val());
console.log($('#address').val());
});
});
Well, you're currently not putting the values anywhere but into the console.log.
I would expect to see something like (let's call your div you want the values to go to, "output"):
$(document).ready(function() {
$('.submitForm').on('click',function(event){
event.preventDefault();
// Borrowing from another response, this is better
// Putting these in variables protects you from
// 1) accidentally modifying your form values
// 2) invalid input, if you add some basic checks, like
// testing to see if the length is > 0, doesn't contain
// bad characters, etc.
var firstName = $('#firstName').val(),
lastName = $('#lastName').val(),
phone = $('#phoneNumber').val(),
address = $('#address').val();
// get a reference to the div you want to populate
var $out = $("#output");
// This is a better way of dealing with this
// because every call to .append() forces DOM
// reparsing, and if you do this too often, it can cause
// browser slowness. Better to put together one string
// and add it all at once.
$out.html("<p>" + firstName + "</p>" +
"<p>" + $('#lastName').val() + "</p>" +
"<p>" + $('#phoneNumber').val() + "</p>" +
"<p>" + $('#address').val() + "</p>");
});
});
$(document).ready(function() {
$('.submitForm').on('click',function(event){
event.preventDefault();
$(this).after('<div>First name: '+$('#firstName').val()+'<br>'+
'Last name: '+$('#lastName').val()+
' .... ');
});
});
First of all, the four lines where you read the .val() but don't do anything with it are essentially wasted cycles, you probably meant to store them in variables:
var firstName = $('#firstName').val();
var lastName = $('#lastName').val();
var phoneNumber = $('#phoneNumber').val();
var address = $('#address').val();
To show them in some other element, use the setter version of .val() for input types, or .text() if it's a display type (div, span, etc):
$('#someOtherElement').text(firstName + '\n' +
lastName + '\n'
phoneNumber + '\n'
address);
$(document).ready(function() {
$('.submitForm').on('click',function(event){
event.preventDefault();
//$('#firstName').val();
//$('#lastName').val();
//$('#phoneNumber').val();
//$('#address').val();
var htmlContent = $('#firstName').val() + '<br />' + $('#lastName').val() + '<br />' + $('#phoneNumber').val() + '<br />' + $('#address').val();
$('#ID_OF_YOUR_DIV_HERE').html(htmlContent);
});
});
Maybe this is what you're after??
You can add it to a div you want with .append(), for example
$("#divYouWantToAddTo").append($('#firstName'));
I don't know where to start... What is all that $('#....').val() in the middle there, wasting time only to throw away the result..?
What is wrong with document.getElementById('...').value instead of wasting time creating an entire jQuery object just to access something trivial?
Adding text to a node is as simple as container.appendChild(document.createTextNode(sometext)); - and if you want to have newlines between them you can also do container.appendChild(document.createElement('br'));.
There is no need for jQuery here at all...

How to create a javascript string in razor

I have seen some posts regarding this topic and a few blogs, but none seem to mention the output I'm getting.
What I want is to generate a google maps map with information on it. Manually entering the information results in the correct information. So that part works.
Where I'm getting stuck is when I'm going to dynamiccaly create the javascript array with the string with the information I want on my map.
The html code I want to get is:
<script type="text/javascript">
var projects = [
['Kantoor 4.1 bestaande bouw', 52.25446, 6.16024700000003, 'Deventer', '', 'adviseurs', 'rating30'],
['School nieuw 4.0', 52.243161, 4.43677860000003, 'Noordwijk', '', 'adviseurs', 'rating30'],
];
Very simple javascript array, which I thought to create with:
<script type="text/javascript">
var projects = [
#foreach (var item in Model)
{
#HttpUtility.JavaScriptStringEncode("['" + item.Gebouwnaam + "', " + item.LocatieLatitude.ToString().Replace(",", ".") + ", " + item.LocatieLongitude.ToString().Replace(",", ".") + ", '" + item.Plaats + "', '" + item.Gebruiksfunctie + "', '" + item.Licentiehouder + "', '" + item.rating + "'],");
}
];
</script>
However this gives me:
<script type="text/javascript">
var projects = [
[\u0027Kantoor 4.1 bestaande bouw\u0027, 52.25446, 6.16024700000003, \u0027Deventer\u0027, \u0027\u0027, \u0027adviseurs\u0027, \u0027rating30\u0027],
[\u0027School nieuw 4.0\u0027, 52.243161, 4.43677860000003, \u0027Noordwijk\u0027, \u0027\u0027, \u0027adviseurs\u0027, \u0027rating30\u0027],
];
</script>
Escaping the single quotes doesn't work.
What am I doing wrong?
Just tried with
<script type="text/javascript">
var projects = [
#Html.Raw("['" + "aaa" + "', '" + "bbb" + "'],")
];
</script>
it worked and showed ...
<script type="text/javascript">
var projects = [
['aaa', 'bbb'],
];
</script>
You don't want to call JavaScriptStringEncode on the entire string, that will also encode your literal indicators (which are being converted to \u0027 in your example). Instead, call it on each item in your array like this:
<script type="text/javascript">
var projects = [
#foreach (var item in Model)
{
String.Format("['{0}',{1},{2},'{3}','{4}','{5}','{6}']",
HttpUtility.JavaScriptStringEncode(item.Gebouwnaam),
HttpUtility.JavaScriptStringEncode(item.LocatieLatitude.ToString().Replace(",", ".")),
HttpUtility.JavaScriptStringEncode(item.LocatieLongitude.ToString().Replace(",", ".")),
HttpUtility.JavaScriptStringEncode(item.Plaats),
HttpUtility.JavaScriptStringEncode(item.Gebruiksfunctie),
HttpUtility.JavaScriptStringEncode(item.Licentiehouder),
HttpUtility.JavaScriptStringEncode(item.rating)
)
}
];
</script>
I believe you could do most of the heavy lifting in .net and leverage Html.Raw to transform the object for you:
#{
var myObj = Model.Select(i => new {
item.Gebouwnaam,
item.LocatieLatitude.ToString().Replace(",", "."),
item.LocatieLongitude.ToString().Replace(",", "."),
item.Plaats,
item.Gebruiksfunctie,
item.Licentiehouder,
item.rating }).ToArray();
}
<script type="text/javascript">
var jsObj = #Html.Raw(Json.Encode(myObj));
</script>
Since it's touched on in this question, HttpUtility.JavaScriptStringEncode() comes in really handy for strings containing newline characters:
#{ var myNetString = "Hi,\r\nMy name is Joe\r\nAnd I work in a button factory"; }
<script type='text/javascript'>
var myJsString = '#HttpUtility.JavaScriptStringEncode(myNetString)';
</script>

Value Javascript Input

how can i transfer the Value from Input 1 in 2 and add some letters?
<script type="text/javascript">
function doit(){
document.getElementById('input2').value=document.getElementById('input1').value;
}
</script>
Input1: 2342
Input2: pcid2342d
Can some one help me?
Just use the + operator to add a string before and after the input value.
<script type="text/javascript">
function doit(){
document.getElementById('input2').value="pcid" + document.getElementById('input1').value + "d";
}
</script>
String concatenation:
document.getElementById('input2').value = "stuff" + document.getElementById('input1').value + "other stuff";
When dealing with numbers you could start by concatenating with empty string to avoid adding numbers together instead of concatenating to strings (because of operator evaluation order):
document.getElementById('input2').value = "" + 1234 + 567 + document.getElementById('input1').value + 89;
Well you seem to have done the work already, all you need is something to click on to execute it:
<button onclick="doit()">click me</button>
Why don't you try something in jQuery?
$("#Anything").click(function() {
$("#Field1").val($("#Field2").val());
});
The "click" is just a assumption =)

Categories