I am trying to dynamically create a Javascript Object and add property and value that are inputted from a text field, the user will type example:
person=name
it will create a new object called person with value name
My code: html
<p class="console">
<input type="text" id="caption"/>
</p>
JavaScript
// my object
myObj = {}
$('#caption').keypress(function(e){
if (e.which == 13) {
// get input value
caption = captionEl.val();
var prop = $.trim(caption.substring(3,caption.indexOf("=")));
var val = $.trim(caption.substring(caption.indexOf("=")+1,caption.length));
// set the property ) NOT WORKING
myObj["'"+prop+"'"]= val;
alert(myObj["'"+prop+"'"]);
}
});
could you help me please to fix it?
myObj = {}
$('#caption').keypress(function(e){
if (e.which == 13) {
// get input value
caption = $(this).val();
var prop = $.trim(caption.substring(3,caption.indexOf("=")));
var val = $.trim(caption.substring(caption.indexOf("=")+1,caption.length));
// set the property ) NOT WORKING
myObj[prop]= val;
alert(myObj[prop]);
}
});
Doesnt seem that you have captionEL defined, use
caption = $("#caption").val();
and it should work
Related
I am trying to get data from a form and append it to a global array but for some reason, the data isn't being added to the array. The code should basically accept the input from the form and store it into the global array. I updated the HTML so you can see the entire syntax. The value should basically be taken from the form and placed into the global array using the "addnew" function.
function addnew()
{
//calculateAge();
//Accept values entered in form
const fname = document.getElementById('fname').value;
const mname = document.getElementById('mname').value;
const lname= document.getElementById('lname').value;
const dob= document.getElementById('dob').value;
const genderM = document.getElementsByName('male').checked;
const genderF = document.getElementsByName('female').checked;
const age = calculateAge.bYear;
const bodyType = document.getElementById('Body Type').value;
const occu= document.getElementById('occu').value;
const height= document.getElementById('height').value;
if (fname==null || fname=="")
{
alert();
}
if(mname==null || mname=="")
{
alert();
}
if (lname==null || lname=="")
{
alert();
}
if(dob==null || dob=="")
{
alert();
}
if (genderM.checked == false || genderF.checked == false){
alert();
}
if (age <=18 || age >=75)
{
alert();
}
if(height>=170 || height<=200)
{
alert();
}
if(bodyType==null || bodyType==""){
alert();
}
if(oocu==null || oocu=="")
{
alert();
}
//Append To array
records.push(fname);
records.push(mname);
records.push(lname);
records.push(dob);
records.push(genderM);
records.push(genderF);
records.push(age);
records.push(bodyType);
records.push(occu);
records.push(height);
for(i=0;i<records.length;i++)
{
console.log(records[i]);
}
//showAll();
//<h1 class="logo"><img src="New folder/logo.jpg" /></h1>
Information.addEventListener('submit', addnew);
}
</script>
```
first of all. name attribute has nothing to do with form element.
second. Information.addEventListener('submit', addnew); has no meaning because Information is not defined.
and to the core. when submiing a form, the page refreshes defaultly, so the addNew function is aborted like all the other variables. in order to prevent it you have to do as follows.
on submit button ad an id attribute:
<button id="submit" type="submit"> Submit </button>
then on top of your JS, get the button element and add an event listener to it:
let submit = document.getElementById('submit');
submit.addEventListener('click', addnew );
and here is the final step. on the addNew function, add an event argument. and on the begining of the function's code, fire the preventDefault method:
function addnew(event) {
event.preventDefault();
// the rest of the code here
}
by the way. you have a typo here. it should be occu.
if (oocu == null || oocu == "") {
alert();
}
good luck!
I am working on a project in JavaScript, which prints out some names pulled from an XML file. I also have 3 textboxes and an update button so that if anyone types in a name in any of the textboxes, they will see the updated names when they hit the button. For example, if I originally have:
George
Mary
John
If the user types in Jane, it should change the output to:
Jane
Mary
John
However, the update button doesn't do anything when it is clicked on. Here is the code for my 3 textboxes and the button:
<div id = "Names">
<input type = "text" id = "nameOne" value = "Enter a name" onClick = "if(this.value == value){this.value = '';}" />
<input type = "text" id="nameTwo" value = "Enter a name" onClick = "if(this.value == value){this.value = '';}" />
<input type ="text" id = "nameThree" value = "Enter a name" onClick = "if(this.value == value){this.value = '';}" />
<input type = "button" id = "btnUpdate" value = "Update Names" onClick = "printNames()" /></div>
And here are the functions I am using:
function getXML(){
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","Names.xml",false);
xmlhttp.send();
return(xmlhttp.responseXML);
}
function printNames() {
var xml = getXML();
var txt = "";
$(xml).find("person").each(function () {
txt += "<div>" + $(this).text() + "</div>";
});
$("body").append(txt);
insertNames(name1, name2, name3);
}
function insertNames(name1, name2, name3) {
var xmlRequest = getXML();
var nameOneTxt = document.getElementById('nameOne').value;
var nameTwoTxt = document.getElementById('nameTwo').value;
var nameThreeTxt = document.getElementById('nameThree').value;
if (nameOneTxt != null || nameTwoTxt != null || nameThreeTxt != null) {
var x = xmlRequest.getElementsByTagName("person")[0].childNodes[0];
x.nodeValue = nameOneTxt;
var y = xmlRequest.getElementsByTagName("person")[0].childNodes[1];
y.nodeValue = nameTwoTxt;
var z = xmlRequest.getElementsByTagName("person")[0].childNodes[2];
z.nodeValue = nameThreeTxt;
}
printNames();
}
printNames();
</script>
The printNames() function reads the names from an XML file and outputs those names using jQuery. It then calls the insertNames() function which takes in 3 parameters (for the three textboxes I have.)
The insertNames function opens an XML connection, and then gets the values for each textbox. If the textbox is not null, then that means the user input a value, in which case, a call to the XML tag is made and updates the existing content to the user input. It then calls the printNames() function which outputs the new contents.
When I test this, I get the original names output, but the update button doesn't do anything. I tried adding a print statement to the insertNames function to find that the function never runs. What am I missing? Any help would be appreciated. Thanks.
I think it is when the function is being loaded. Check this
Fiddle.
I have reduced your printNames call to this
function printNames(){
alert(1);
}
If you leave it to run at default onLoad it doesn't work. If you change the load time to No wrap -in Body it works fine.
Haven't seen your code, but check where you are loading the function in relation to the onclick. The manual printNames() call at the bottom of the script will work whereas the onclick printNames() call will not.
I am assigning value on keyup event in a property of javascript object. It is printing null in console.
function check(id){
var me= this;
this.ID= null;
this.matchName= this.ID.substr(this.ID.lastIndexOf('_'));
this.first= function (){
alert(me.matchName)
}
this.second= function (){
alert(1)
}
this.touch= function (){
$(id).find('input').keyup(function(e){
me.ID= this.id;;
if(e.keyCode==13){
id.indexOf('first')>-1? me.first(): me.second();
}
})}
}
Body
<div class="first">
<input type="text" id="val_00_01" />
</div>
<div class="two">
<input type="text" id="val_00_02"/>
</div>
<script type="text/javascript">
var first= new check('.first');
var two= new check('.two');
first.touch()
two.touch()
</script>
Well this is one broken part (unless it's intentional?)
Set the ID property to null
this.ID= null;
Try to access the property you just set equal to null
this.matchName= this.ID.substr(this.ID.lastIndexOf('_'));
This code is running in the initialization (constructor) of your Check class and will error out.
Here's what I think you want, with better formatting so not to cause eye-bleeding.
// capitalize first letter of class name
function Check(className){ // use a prop/descriptive parameter name
var me = this; // set your variable "me" to class instanced
this.ID = null; // INITIALIZE your ID and matchName variables
this.matchName = null;
this.first = function (){
alert(me.matchName)
};
this.second = function (){
alert(1)
};
this.touch = function (){
// get the element with class=className
// find the input inside of it
// set an onkeyup handler to the input element
$(className).find('input').keyup(function(e){
me.ID = this.id;; // set the ID variable to the INPUT element's ID property
// set matchName to the last part of the input's ID property
// matchName will be "01" or "02" in this case
me.matchName = this.ID.split("_")[this.ID.split("_").length - 1];
if(e.keyCode==13){
id.indexOf('first') > -1 ? me.first(): me.second();
}
});
};
}
...
var first = new Check('.first');
var two = new Check('.two');
first.touch();
two.touch();
I am trying to do some simple form validation using javascript object values. I know it's not "ideal", but I'm just working with a simple form that doesn't need to be iron-clad.
Please see my fiddle example: http://jsfiddle.net/6dXd7/3/
I am trying to make sure that each form field has a value. If so, set the value for myObj.fieldID to yes.
Then, when the form is submitted, check every existing myObj.XXX and be sure all their values are yes.
In my example, I am having trouble creating the object, and I don't know how to cycle through all the objects when the submit button is pressed without specifying each one by name.
Here's the code in the jsfiddle example linked to above:
<script>
$(document).ready(function () {
var myObj = {};
$("input.checkblank").blur(function () {
var inputID = $(this).attr("id");
var contents = $("input#" + inputID).val();
if (contents == "") {
$(myObj).data(inputID, "no");
} else {
$(myObj).data(inputID, "yes");
}
});
$("#verify").click(function () {
if (myObj.first && myObj.second == "yes") {
// ***** Trying to get it to scan through ALL existing myObj's and make sure all their values are "yes" *****
$('.results').text('all good');
} else {
$('.results').text('not good');
}
});
});
</script>
<input type="text" name="first" id="first" class="checkblank"><br />
<input type="text" name="second" id="second" class="checkblank">
check<br />
<p class="results"> </p>
You were storing field info in jQuery DATA and trying to check them later not in the same place...
var obj = {}
$(obj).data('a','1');
console.log(obj.a); //this will log null, cause there's no attribute 'a' in 'obj'
console.log($(obj).data('a')); //this will log '1' :]
instead do this, you should store you data in attributes from native object like this:
var obj = {}
obj['a'] = '1'; //obj.a = '1' work's too
console.log(obj.a); //now it log '1' :]
Also, your verification function is wrong.. it only check if first exists inside myObj and if second exists and is equal to "yes". So your verification function should be something like this:
$("#verify").click(function() {
var allFieldsOK = false;
for ( var field in checkedFields ) {
if ( !(allFieldsOK = checkedFields[field] ) ) break;
}
$('.results').text( allFieldsOK ? 'all good' : 'not good' );
});
Here is an update to you jsFiddle, it is working for you purpose and should work if you add more input fields with the class checkblank :]
http://jsfiddle.net/6dXd7/5/
replace this
$("#verify").click(.........});
with this
$("#verify").click(function() {
var flag=true;
$('.checkblank').each(function(){ //check all elements with class checkblank
if($(this).val().length==0) //set flag false if anyone of them is blank
flag=false;
})
if (flag) {
$('.results').text('all good');
} else {
$('.results').text('not good');
}
});
...it should work
I'm trying to have two functions checking each form input, one for onchange() and the other for onkeypress(); my reason for this would be to show if the input was valid once you leave the input field using onchange() or onblur(), and the I also wanted to check if the input field was ever empty, to remove the message indicating that bad input was entered using onkeypress() so that it would update without having to leave the field (if the user were to delete what they had in response to the warning message.)
It simply isn't working the way I intended, so I was wondering if there was something obviously wrong.
My code looks like this:
<form action="database.php" method = post>
Username
<input type='text' id='un' onchange="checkname()" onkeypress="checkempty(id)" />
<div id="name"></div><br>
.....
</form>
And the Javascript:
<script type="text/javascript">
function checkname() {
var name = document.getElementById("un").value;
var pattern = /^[A-Z][A-Za-z0-9]{3,19}$/;
if (name.search(pattern) == -1) {
document.getElementById("name").innerHTML = "wrong";
}
else {
document.getElementById("name").innerHTML = "right!";
}
}
function checkempty(id) {
var temp = document.getElementById(id).value;
if (!temp) {
document.getElementById("name").innerHTML = '';
}
}
</script>
Per your clarification in the comments, I would suggest using the onkeyup event instead of onkeypress (onkeypress only tracks keys that generate characters - backspace does not). Switching events will allow you to validate when the user presses backspace.
Here's a working fiddle.
Edit:
See this SO question for further clarification: Why doesn't keypress handle the delete key and the backspace key
This function should below should check for empty field;
function checkempty(id) {
var temp = document.getElementById(id).value;
if(temp === '' || temp.length ===0){
alert('The field is empty');
return;
}
}
//This should work for check name function
function checkname() {
var name = document.getElementById("un").value;
var pattern = /^[A-Z][A-Za-z0-9]{3,19}$/;
if (!name.test(pattern)) {
document.getElementById("name").innerHTML = "wrong";
}
else {
document.getElementById("name").innerHTML = "right!";
}
}