Assigning initial values using the with statement - javascript

The following works:
var Person = {};
Person.FirstName = '';
Person.LastName = '';
with (Person) {
FirstName = 'Phillip',
LastName = 'Senn';
}
log(Person);
But I want to remove lines 2-3.

What about:
var Person = {FirstName:'Philip', LastName:'Senn'};
log(Person);

Related

I can only store the one student details to the local storage.How can i store multiple student details using the same form in localstorage?

$("#smtbtn").click(function(){
var username = $("#username").val()
var email = $("#email").val()
var phone = $("#phone").val()
var textcalendar = $("#text-calendar").val()
var age = $("#age").val()
var pic = $("#pic").val()
var address = $("#address").val()
var m1 = $("#m1").val()
var m2 = $("#m2").val()
var skill = $("#skill").val()
var student= [username,email,phone,textcalendar,age,pic,address,m1,m2,skill];
localStorage.setItem("studentdetails", JSON.stringify(student));
var retrievedData = localStorage.getItem("studentdetails");
var movies1 = JSON.parse(retrievedData);
console.log(movies1);
})
You can simply add another level, like this:
var students = localStorage.getItem("students");
if (students) {
students = JSON.parse(students);
} else {
students = {};
}
students[username] = [username,email,phone,textcalendar,age,pic,address,m1,m2,skill];
localStorage.setItem("students", JSON.stringify(students));
and then if you call getItem you will have an object of key-value pairs where the key is the username and the value is the student object.
EDIT
Testing the feature:
var students = localStorage.getItem("students");
if (students) {
students = JSON.parse(students);
} else {
students = {};
}
console.log(students);
students["ha"] = ["ha", "haha"];
localStorage.setItem("students", JSON.stringify(students));
Set to localstorage:
students[username] =
[username,email,phone,textcalendar,age,pic,address,m1,m2,skill];
localStorage.setItem("students", JSON.stringify(students));
Get from localstorage:
var students = localStorage.getItem("students");
if (students) {
students = JSON.parse(students);
} else {
students = {};
}

JavaScript beginner: why does this not work?

My html page is not responding to this code I wrote in JS, i'm a total beginner, and just started learning JS, can somebody tell me why this doesn't work?
/* this is a practice file that'll play with js
nothing strange to look at here folks! */
var firstName = 'Steven';
var lastName = 'Curry';
var fullName = firstName + ' ' + lastName;
function Hotel(HotelName){
this.HotelName = HotelName;
this.numRooms = 20;
this.numGuests;
this.checkAvailability {
if(numRooms != 20 ){
return true;
}
else{
return false;
}
}
this.getHotelName = function(){
//can it work with this dot operator?
return this.HotelName;
}
}
var HiltonHotel = new Hotel('Hilton');
var hName = document.getElementById('hotelName');
hName.textContent = getHotelName();
var el = document.getElementById('name');
el.textContent = fullName;
<!DOCTYPE html>
<html>
<body>
<div id = 'greeting'> Hello
<span id="name">friend</span>!
<h1>Welcome To the <span id = 'hotelName'>Hyatt</span>
</div>
<script
src = "https://stacksnippets.net/js">
</script>
</body>
</html
I'm pretty sure it's ordering and my syntax i need to work on, any advice is greatly appreciated thank you!
Few misunderstandings:
checkAvailability is a function, you are missing parens.
while accessing the getHotelName function, you have to refer to the HiltonHotel variable, to be able to access and call that function.
few minor errors in your html code, while operating in code snippet, you don't have to add a separate script, it's connected together by default.
var firstName = 'Steven';
var lastName = 'Curry';
var fullName = firstName + ' ' + lastName;
function Hotel(HotelName) {
this.HotelName = HotelName;
this.numRooms = 20;
this.numGuests;
this.checkAvailability = function() { // it's a function (missing parens)
if (numRooms != 20) {
return true;
} else {
return false;
}
}
this.getHotelName = function() {
return this.HotelName;
}
}
var WeiHotel = new Hotel('Hilton');
var hName = document.getElementById('hotelName');
hName.textContent = WeiHotel.getHotelName(); // refer to the `WeiHotel` variable
var el = document.getElementById('name');
el.textContent = fullName;
<div id='greeting'> Hello
<span id="name">friend</span>!
<h1>Welcome To the <span id='hotelName'>Hyatt</span></h1>
</div>
An extension to the answer of #KindUser:
You're not using closures anywhere in this class to store some private state. Therefore you should attach the methods to the prototype and not to the instance itself. It's more economic, because now all instances share one function, not one per instance. And the JS engine can optimize that better.
Then, you have another error in checkAvailability: numRooms needs to be addressed as this.numRooms because it is a property of this instance, and there is no variable with this name.
And one about style. If you have something like
if(condition){
return true;
}else{
return false;
}
you can simplify this to:
return condition;
//or if you want to enforce a Boolean value,
//but your condition may return only a truthy/falsy value:
return Boolean(condition);
//sometimes also written as:
return !!(condition);
Next. Stick to the coding standards. In JS a variable/property starting with an uppercase letter would indicate a class/constructor, therefore HotelName, HiltonHotel, WeiHotel are misleading.
And I find the property name hotelName redundant and counter-intuitive. Imo you have a Hotel, it has a name, but that's just an opinion.
var firstName = 'Steven';
var lastName = 'Curry';
var fullName = firstName + ' ' + lastName;
function Hotel(name) {
this.name = name;
this.numRooms = 20;
this.numGuests;
}
Hotel.prototype.checkAvailability = function() {
return this.numRooms !== 20;
}
Hotel.prototype.getHotelName = function() {
return this.name;
}
var hotel = new Hotel('Hilton');
var hName = document.getElementById('hotelName');
hName.textContent = hotel.getHotelName(); // refer to the `weiHotel` variable
var el = document.getElementById('name');
el.textContent = fullName;
<div id='greeting'> Hello
<span id="name">friend</span>!
<h1>Welcome To the <span id='hotelName'>Hyatt</span></h1>
</div>
or as an ES6 class (and some playin around):
class Person{
constructor(firstName, lastName){
this.firstName = firstName;
this.lastName = lastName;
}
//this is a getter, you can read it like a property
get fullName(){
return this.firstName + " " + this.lastName;
}
//this function is implicitely called whenever you try to convert
//an instance of `Person` into a string.
toString(){
return this.fullName;
}
}
class Hotel{
constructor(name) {
this.name = name;
this.numRooms = 20;
this.numGuests;
}
checkAvailability() {
return this.numRooms !== 20;
}
getHotelName() {
return this.name;
}
}
var steve = new Person('Steven', 'Curry');
var hotel = new Hotel('Hilton');
var hName = document.getElementById('hotelName');
hName.textContent = hotel.getHotelName(); // refer to the `weiHotel` variable
var el = document.getElementById('name');
el.textContent = steve.fullName;
//this uses the `toString()` method to convert the `Person` steve into a string
//for people, this makes sense, for the Hotel you'd want to think:
// - where do I want to use this?
// - and what should this string contain?
console.log("Hello, I'm " + steve + " and I'm at the "+ hotel.name);
<div id='greeting'> Hello
<span id="name">friend</span>!
<h1>Welcome To the <span id='hotelName'>Hyatt</span></h1>
</div>

Key name in associative array

I'm trying to add items to an associative array but my key name is not being generated properly. My code is as follows:
var room_name = $('#room_name').val();
var item_name = $('#item_name').val();
var item_description = $('#item_description').val();
roominventory[room_name] = { item_name : item_description };
What is happening is I am getting
{
"Correct room name": {
"item_name": "correct item description"
}
}
Everything works except the item_name. I would like the key name to be the value of item_name but instead I'm just getting the text item_name.
Any ideas what I'm doing wrong?
You can't use variables in the object key with the syntax you're using, as they are taken literally. You need to use bracket notation as you are in the setter of roominventory. Try this:
var room_name = $('#room_name').val();
var item_name = $('#item_name').val();
var item_description = $('#item_description').val();
var obj = {};
obj[item_name] = item_description;
roominventory[room_name] = obj;
As an alternative you can use
roominventory[room_name] = {[item_name] : item_description};
As Rory pointed out, you can't use variables in key. you have to use an object which holds the key and value:
//wrong one
var roominventory = {};
var room_name = "something";
var item_name = "something item";
var item_description = "something description";
roominventory[room_name] = {item_name : item_description};
console.log(roominventory);
//correct way
var roominventory1 = {};
var room_name = "something";
var item_name = "something item";
var item_description = "something description";
var obj = {};
obj[item_name] = item_description;
roominventory1[room_name] = obj;
console.log(roominventory1);
https://jsfiddle.net/u2j42wsv/
var room_name = $('#room_name').val();
var item_name = $('#item_name').val();
var item_description = $('#item_description').val();
roominventory = new Array();
roominventory[room_name] = {};
roominventory[room_name][item_name] = item_description;

jQuery assigning value to array giving error Undefined variable

I'm assigning values to array in forloop But it gives an error that array variable is undefine. following is my code.
$(document).ready(function(){
$("#SubmitBtn").live('click',function(){
var cnt = $("#TotalCnt").val();
var data = [];
for(var i=1; i<=cnt; i++)
{
var fname = $('#fname_'+i).val();
var lname = $('#lname_'+i).val();
var address = $('#address_'+i).val();
data[i]["fname"] = fname;
data[i]["lname"] = lname;
data[i]["address"] = address;
}
});
});
when I'm assigning value to array it gives error "data[i] is undefined"
Try to create an empty object first, because initially data[i] is undefined. And undefined does not contains any property under it.
$(document).ready(function(){
$("#SubmitBtn").live('click',function(){
var cnt = $("#TotalCnt").val();
var data = [];
for(var i=1; i<=cnt; i++)
{
var fname = $('#fname_'+i).val();
var lname = $('#lname_'+i).val();
var address = $('#address_'+i).val();
data[i] = {};
data[i]["fname"] = fname;
data[i]["lname"] = lname;
data[i]["address"] = address;
}
});
});

javascript regex, split user's full name

I have user's firstname and lastname in one string, with space between
e.g.
John Doe
Peter Smithon
And now I want convert this string to two string - firstname and lastname
John Doe -> first = John, last = Doe
John -> first = John, last = ""
[space]Doe -> first = "", last = Doe.
I am using next code
var fullname = "john Doe"
var last = fullname.replace(/^.*\s/, "").toUpperCase().trim(); // john
var first = fullname.replace(/\s.*$/, "").toUpperCase().trim(); // Doe
and this works well for two-word fullname. But if fullname has one word, then I have problem
var fullname = "john"
var last = fullname.replace(/^.*\s/, "").toUpperCase().trim(); // john
var first = fullname.replace(/\s.*$/, "").toUpperCase().trim(); // john
http://jsfiddle.net/YyCKx/
any ideas?
Use split + shift methods.
var parts = "Thomas Mann".split(" "),
first = parts.shift(),
last = parts.shift() || "";
So in case of single word name it will give you expected result:
last = "";
Use this code:
You'll need to change the line: splitFullName("firstName","lastName","fullName"); and make sure it includes the right field IDs from your form.
function splitFullName(a,b,c){
String.prototype.capitalize = function(){
return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
};
document.getElementById(c).oninput=function(){
fullName = document.getElementById(c).value;
if((fullName.match(/ /g) || []).length ===0 || fullName.substring(fullName.indexOf(" ")+1,fullName.length) === ""){
first = fullName.capitalize();;
last = "null";
}else if(fullName.substring(0,fullName.indexOf(" ")).indexOf(".")>-1){
first = fullName.substring(0,fullName.indexOf(" ")).capitalize() + " " + fullName.substring(fullName.indexOf(" ")+1,fullName.length).substring(0,fullName.substring(fullName.indexOf(" ")+1,fullName.length).indexOf(" ")).capitalize();
last = fullName.substring(first.length +1,fullName.length).capitalize();
}else{
first = fullName.substring(0,fullName.indexOf(" ")).capitalize();
last = fullName.substring(fullName.indexOf(" ")+1,fullName.length).capitalize();
}
document.getElementById(a).value = first;
document.getElementById(b).value = last;
};
//Initial Values
if(document.getElementById(c).value.length === 0){
first = document.getElementById(a).value.capitalize();
last = document.getElementById(b).value.capitalize();
fullName = first + " " + last ;
console.log(fullName);
document.getElementById(c).value = fullName;}}
//Replace the ID's below with your form's field ID's
splitFullName("firstName","lastName","fullName");
Source: http://developers.marketo.com/blog/add-a-full-name-field-to-a-marketo-form/
You can use split method
var string = "ad";
var arr = string.split(" ");
var last = arr[0];
var first = arr[1];
if(first == null){
first = "";
}
alert(last + "\n" + first)​;​
If in every situation you have just "first last" you could use:
var string = "john "
var i = string.split(" ");
alert("first: "+i[0]+ "\n"+ "last: " + i[1]);
I know that this has already been replied to and marked as answered but i just want to note that if you do still want to use regex you can change the "last" expression:
var last = string.replace(/^[a-zA-Z]*/, "").toUpperCase().trim();
jQuery( window ).load(function() {
jQuery("#FullNametest").change(function(){
var temp = jQuery(this).val();
var fullname = temp.split(" ");
var firsname='';
var middlename='';
var lastname = '';
firstname=fullname[0];
lastname=fullname[fullname.length-1];
for(var i=1; i < fullname.length-1; i++)
{
middlename = middlename +" "+ fullname[i];
}
jQuery('#FirstName').val(firstname);
jQuery('#LastName').val(lastname);
});
});
var str='John';
var str2='Peter Smithon';
var str3='Peter';
var words=str.split(/\s+/g,2);
var first=words[0];
var last=words[1]||'';
alert(first+' '+last);

Categories