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();
Related
I need to insert a user input number value into the "41" var value=getClosestNum(41,intarray);.
I know "41" needs to be calling the name or the id from the input but my rusty Javascript attempts always seem to result with = 1. I've tried several getDocument, getID variants, sub functions, etc without success.
Ideally, the result would be instantaneous by using onChange on the input field without page reload.
Yes, it has to be JavaScript for incorporation later.
<html>
<head>
<title>Find nearest value in javascript</title>
<script language="javascript">
// big array to come, example numbers
var intarray=[1,2,3,5,7,9,11,33,40,42,44,55,66,77,88];
// Now this function used to find out the close value in array for given number
function getClosestNum(num, ar)
{
var i = 0, closest, closestDiff, currentDiff;
if(ar.length)
{
closest = ar[0];
for(i;i<ar.length;i++)
{
closestDiff = Math.abs(num - closest);
currentDiff = Math.abs(num - ar[i]);
if(currentDiff < closestDiff)
{
closest = ar[i];
}
closestDiff = null;
currentDiff = null;
}
//returns first element that is closest to number
return closest;
}
//no length
return false;
}
</script>
</head>
<body>
<form>
<input type="number" id="test" name="test" onChange="?">
</form>
<script language="javascript">
document.write("Array: "+intarray+"<br>");
document.write("Value to find 41 <br>");
// CODE TO CHANGE "41" to id or named input
// 41 to reference input field
var value=getClosestNum(41,intarray);
document.write("Response Received "+value);
</script>
</body>
</html>
As I understand it, you are trying to use the input element to take a number, and you would like to return the closest number to that input from the array.
I registered a function that fires on an 'input' event. Try this:
HTML
Add the following element to see the output of the function. You can redirect it later to wherever you need it.
<p id="output"></p>
JavaScript
// wrap in an onload function to ensure
// that the elements exist before searching for them
window.onload = () => {
// cache of elements on the page you want to use
const testInputElement = document.getElementById('test');
const outputElement = document.getElementById('output');
// create a function that will fire whenever input is received
testInputElement.addEventListener('input', (event) => {
outputElement.innerHTML = getClosestNum(event.target.value, intarray);
})
};
onInput vs addEventListener('input')
Adding onInput directly to the HTML inside an element is not as secure as registering a function programmatically via addEventListener(). If you have a function called, say, handleInput(), simply pass that name to addEventListener as an argument like so
addEventListener('input', handleInput);
Your code with the changes
<html>
<head>
<title>Find nearest value in javascript</title>
<script language="javascript">
// big array to come, example numbers
var intarray=[1,2,3,5,7,9,11,33,40,42,44,55,66,77,88];
// Now this function used to find out the close value in array for given number
function getClosestNum(num, ar)
{
var i = 0, closest, closestDiff, currentDiff;
if(ar.length)
{
closest = ar[0];
for(i;i<ar.length;i++)
{
closestDiff = Math.abs(num - closest);
currentDiff = Math.abs(num - ar[i]);
if(currentDiff < closestDiff)
{
closest = ar[i];
}
closestDiff = null;
currentDiff = null;
}
//returns first element that is closest to number
return closest;
}
//no length
return false;
}
</script>
</head>
<body>
<form>
<input type="number" id="test" name="test" onChange="?">
</form>
<p id="output"></p>
<script language="javascript">
document.write("Array: "+intarray+"<br>");
document.write("Value to find 41 <br>");
// CODE TO CHANGE "41" to id or named input
// 41 to reference input field
var value=getClosestNum(41,intarray);
document.write("Response Received "+value);
// wrap in an onload function to ensure that the elements exist before searching for them
window.onload = () => {
// cache of elements on the page you want to use
const testInputElement = document.getElementById('test');
const outputElement = document.getElementById('output');
// create a function that will fire whenever input is received
testInputElement.addEventListener('input', (event) => {
outputElement.innerHTML = getClosestNum(event.target.value, intarray);
})
};
</script>
</body>
</html>
You're getting rid of your reference to the closestDiff on every loop, you need to keep that value throughout the loop and update it when the diff decreases.
function getClosestNum(num, arr) {
var closest;
if (arr.length > 0) {
closest = arr[0];
var diff = Math.abs(arr[0] - num);
for (var i = 1; i < arr.length; i++) {
var currentDiff = Math.abs(arr[i] - num);
if (diff > currentDiff) {
closest = arr[i];
diff = currentDiff;
}
}
}
return closest;
}
I can set the value easily, below is the code:
document.getElementById("set").onclick = function() {
var d = document.getElementById("text").value;
chrome.storage.sync.set({ "data" : d }, function() {
if (chrome.runtime.error) {
console.log("Runtime error.");
}
});
window.close();
}
sync.set is working fine. I want the sync.get function to work on a different domain whose input field is like this
<input class="valueinput" type="text" name="Text_Value" size="12" value="" onfocus="select()" maxlength="6">
As you can see there is no id assigned. I am not getting the stored value in the textbox above. Below is the get code I am using.
function get() {
chrome.storage.sync.get("data", function(items) {
if (!chrome.runtime.error) {
console.log(items);
var textarea = document.getElementsByName("Text_Value");
textarea.value = items.data;
}
});
}
get();
The input box does not have any id. Please help.
document.getElementsByName returns an array-like NodeList collection, not a single element as you can see for example when debugging the code step by step.
var textarea = document.getElementsByName("Text_Value")[0];
if (textarea) { // always check if the element exists!
textarea.value = items.data;
}
I have an issue with automatic name for input, I'll try to explain what i need to do. i have an id, that I get it from an external function. I need to use this numeric id to create another function like that.
var id = 10; // this is the id (from external function)
var value = "n"+bar.toString(); // (I try to cast the id as string)
$("input[name="+value+"]").on('change', function() { // use the cast value to name my input.
alert($("input[name="+value+"]:checked", "#myForm").val());
});
When I try to do that I get undefined, but when I change the id like that var id ="10" I get the correct answer, but I have a numeric input. Please help me figure out how to solve this problem.
Did you want something like this? This is based on an assumption that you have checkboxes within a form!
var ids = [10, 20, 30, 11, 12];
$.each(ids, function(index, val) {
var id = val;
var value = "n" + id; // `.toString` is not required!
$("#myForm").find("input[name='"+value+"']").on('change', function() {
if ($(this).is(":checked")) {
alert( $(this).val() );
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<input type="checkbox" name="n10" value="10" />
<input type="checkbox" name="n11" value="11" />
<input type="checkbox" name="n12" value="12" />
</form>
use this code no need for id.toString()
var id = getId(); // this is the id (from externel function)
var value = "n" + id;
$("input[name="+value+"]").on('change', function() {
alert($("input[name="+value+"]:checked").val()); //change this selector accordingly
});
function getId() {
return 10;
}
here is the fiddle
https://jsfiddle.net/rrehan/srhjwrz4/
Try below code:
var id = 10; // this is the id (from externel function)
var value = id.toString(); // (i try to cast the id as string)
console.log(value);
$("input[name="+value+"]").on('change', function() { // use the casted value to name my input.
alert($("input[name="+value+"]:checked", "#myForm").val());
});
Demo Link
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
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