I have a loop for my input checkboxes (see below).
<cfloop query="qGetCBList">
<input name="#qGetCBList.CheckBox#" type="checkbox" id="#qGetCBList.CheckBox#"onclick="CheckBoxSelect('#qGetCBList.CBNum#','#qGetCBList.CheckBox#','#qGetCBList.RecordCount#');"> #qGetCBList.CBDesc#
<br /><br />
</cfloop>
and my javascript function is,
<script language="JavaScript">
CheckBoxSelect = function(CB,cbID,rCnt){
var myVar_CB=CB;
var myVar_CB_ID=cbID;
var myVar_RCNT=rCnt;
if(myVar_CB == 2) //"Chemical(s)........."
{
for(i=1;i<=myVar_RCNT;i++){
var myVar_CB_ID_FMT="cb"+i; //check box ID format
if(i!=2){
//alert(myVar_CB_ID_FMT);
document.getElementById("myVar_CB_ID_FMT").disabled=true;
}
}
}
else{
alert('good to go');
}
}
</script>
what's happening here is, if the selected checkbox is 2 (which is the CBNum), then I want all other checkboxes to be disabled.
P.S. This is the bind page of the main page. When I un-comment my alert tag, it gives me the correct CBNums, but the disabling is not working. If it any useful I'm using CF8.
Feedbacks and/or alternate methods are appreciated. Thank you.
I know nothing about ColdFusion but the basic JavaScript tips you can use are:
Check the return value of document.getElementById(); don't assume it'll always return a node you can disable.
Most browsers have a built-in or downloadable debugger that allows you to inspect variables. Use that instead of plain alerts. E.g.:
console.log(myVar_CB_ID_FMTT, document.getElementById(myVar_CB_ID_FMT));
getElementById("myVar_CB_ID_FMT") is looking for an element called myVar_CB_ID_FMT. Does that element exist? No. Your variable myVar_CB_ID_FMT is not going to be evaluated as getElementById just sees it as the string "myVar_CB_ID_FMT".
Try document.getElementById("cb"+i)
The id in getElementById(id) is case sensitive so ensure that "cb"+i exists.
#Barry Jordan answer kinda woke me up and I was error checking along the line #Álvaro G. Vicario mentioned, I then finally figured out what's going on.
In my loop when I trim my id value ...id="#trim(qGetCBList.CheckBox)#"... it works.
of course it had be something simple stupid and my fault.
Thanks guys for support, you all rock.
Related
I have a bunch of HTML number inputs, and I have grabbed them by
x=document.querySelectorAll('input[type="number"]');
I then try and iterate through this with a for-loop, and apply an onkeyup function. The function is this:
t=function(elem){
elem.onkeyup=function(e) {
if(!/[\d\.]/.test(String.fromCharCode(e.which))) {
elem.value='';
}
};
};
Basically, what it does is clear the value of the input if there is a letter typed in. I know I can apply it via HTML:
<input type='number' onkeyup='t(this)'/>
But how can I do it with Javascript? I tried iterating through it with:
x=document.querySelectorAll('input[type="number"]');
for(i=0; i<x.length; i++){
x[i].onkeyup=t(this);
}
but it doesn't work. What am I doing wrong? How can I do this? Please regular JavaScript answers only, no jQuery or other frameworks/libraries.
change
x[i].onkeyup=t(this);
to
x[i].onkeyup=t(x[i]);
because this isn't what you want it to be
Apologies, all. I found my answer. Agreeing with Jaromanda X, I needed to change
x[i].onkeyup=t(this);
to
x[i].onkeyup=t(x[i]);
This (pun intended ;)was part of the problem, but the main problem was that the valid property name is
keyup=function();
and not
onkeyup=function(){}'
I am in the process of learning JavaScript and jQuery, so apologies if any of this sounds naive or obvious. I started what I thought was a fairly simple project to practice and hopefully learn something in the process.
What I want to do is this: the user inputs a sentence and hits a submit button. The sentence gets added to a list of other sentences submitted by people (preferably on a separate file, preferably encrypted, but not necessary). Then, the website grabs a random sentence from the list and displays it.
I am not asking on how to build all of this. I have already put most of it together, but I am including it here for reference.
I have a separate javascript file with the array of quotes.
var quotes=new Array();
quotes[0]="<p>Quote 1</p>";
quotes[1]="<p>Quote 2</p>";
quotes[2]="<p>Quote 3</p>";
quotes[3]="<p>Quote 4</p>";
quotes[4]="<p>Quote 5</p>";
quotes[5]="<p>Quote 6</p>";
quotes[6]="<p>Quote 7</p>";
Then I randomly display one using this:
function getQuote(){
var thisquote=Math.floor(Math.random()*(quotes.length));
document.write(quotes[thisquote]);
}
And adding <script> getQuote(); </script> to the html.
This all works fine.
The part I cannot seem to figure out is taking user input and adding it to the jQuery array. I am using a contenteditable div instead of an <input> because I want it to have multiple lines of text and have a character limit, which as far as I know can only be done with a contenteditable div (according to the research I did at the time, I may be wrong).
I have looked around and tried many if not all the examples I found of how to do this, and none of them worked. This is the last method I tried, if it helps:
$(".submit").click(function() {
quotes[quotes.length] = document.getElementsByClassName("input").value;
});
So, to reiterate, I want to take user input and add it to a JavaScript array. I have scoured stackoverflow and the interet but nothing has worked. Please help!
UPDATE: Arvind got it right. I still have a lot to learn, and it seems I need to read up on localstorage and cookies. I will also need to use PHP to save the sentences on the server. Thank you to all who answered!
Problem is document.getElementsByClassName("input") gives you a NodeList and not just a single html element. So if you do this document.getElementsByClassName("input").value, you will end up quotes as [undefined, undefined ... undefined]. Assuming you have single element with the class name input, go with index 0. Also as you stated that you are using div with attribute contenteditable, you may try this instead. document.getElementsByClassName("input")[0].innerHTML
Try this example.
var quotes = localStorage.getItem('quotes'); //get old, if any, gives you string
quotes = quotes ? [quotes] : []; // if got quotes then make it as array else make new array
$(function() {
var quote = $('#quote'); //get the quote div
quote.html(quotes.join('') || quote.html()); //set the default text
$('#btn').on('click', function(e) {
quotes.push(quote.html());
localStorage.setItem('quotes', quotes.join('')); //save the quotes
alert(quotes.join(''));
});
});
#quote {
border: 1px solid grey;
height: 100px;
overflow: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div contenteditable='' id='quote'>
<ol>
<li>Quote 1</li>
<li>Quote 2</li>
</ol>
</div>
<input type='button' id='btn' value='Submit' />
P.S.
In order to preserve the old quotes you may possibly use cookie, localStorage, etc.
Are these "quotes" being saved locally?
Yes, to share it among several users visiting by different browsers, you have to save it with the server script like PHP, Java, ASP, etc. Here you can either use ajax, if you wana avoid page reload on submit, else you can go for form submit.
$(".submit").click(function() {
quotes[quotes.length] = document.getElementsByClassName("input").value;
});
should be
$(".submit").click(function() {
quotes.push(document.getElementsByClassName("input").text());
});
EDIT: With a content editable div you need to use text() instead. Here is an example fiddle. https://jsfiddle.net/
var quotes=[];// better
// function to add to array
function addQuote(myquote){
quotes.push('<p>'+myquote+'</p>');
}
addQuote("Quote 1");
addQuote("Quote 2");
addQuote("Quote 3");
addQuote("Quote 4");
addQuote("Quote 5");
addQuote("Quote 6");
addQuote("Quote 7");
addQuote("Quote 8");
$(".submit").on('click',function() {
addQuote(document.getElementsByClassName("input")[0].value);
});
NOTE: suggest NOT using the "input" class name and use some other one as that might be confusing to others at some point later (confused by element named input)
I also added the paragraph tags as that would provide a consistent pattern for your input text. Assumption on my part however.
NOTE I also assume that the element IS an input type with the .value since that is NOT provided (the markup)
I am sure this is a simple question.
To begin really playing with javascript and understand it I need to have the environment to see what my output is. I have done lessons in javascript but need to actually get the HTML and javascript talking.
What I am looking to do:
Have a user input information into an text box and have it show the result in the html.
is the sky blue? Yes (makes true be displayed on my HTML)
is the sky blue? No (makes false be displayed in my HTML)
currently i have no idea if my javascript is doing anything!
Here is my code:
HTML:
<form action="" onsubmit="return checkscript()">
<input type="text" name="value">
<input type="submit" value="Submit">
Javascript:
function checkscript() {
for (i=0;i<4;i++) {
box = document.example.elements[i];
if (!box.value) {
alert('You haven\'t filled in ' + box.name + '!');
box.focus()
return false;
}
}
return true;
}
document.write(box);
I am so confused but need to see the results of what i am doing to see where to fix things, i tried using console in chromes inspect elements function but this has confused me more.
Can someone help and clean the code up to make sense by labelling everything as what they do?
box? check script?
Thanks :)
I updated the jsfiddle I had made for you. It's a working version that might get you started.
HTML
<!-- I avoided all the mess of forms, since that submits to a server, and that's more than you want right now. Note that I added ids to each input. Ids make it very easy to access the elements later. -->
<input type="text" name="value" id="fillIn">
<input type="button" value="Submit" id="button">
JS
// My methodology here is totally different, since I directly get the element I care about
function checkscript() {
// find the element in the DOM
var box = document.getElementById("fillIn");
// check for a value
if (box.value) {
// if there is one, add a new div. That's probably not what you'll want in the long run, but it gives you something to work with (and seems to match your old idea of using document.write. I have never yet used document.write, though others with more experience than I may like the concept better.
// This creates a new element. If you press F12 and look at this in your debugger, you'll see it actually appear in the HTML once it's appended
var newElement = document.createElement("div");
// Set the value to what you want
newElement.innerHTML = box.value;
document.body.appendChild(newElement);
} else {
alert('You haven\'t filled in ' + box.name + '!');
box.focus()
// No returns necessary, since we're not dealing with formsubmittal.
}
}
// This hooks up the function we just wrote to the click event of the button.
document.getElementById("button").onclick = checkscript;
This may or may not be what you want, but it's at least a place to get started.
A few things to start out:
1.) Make sure all elements have end tags
<input type="text" name="value" />
Note backslash at end of tag.
2.) You are using a form tag, which submits a form to a server side component.
Suggest you need to use the onclick event. Which is available on all input controls. Suggest you start with buttons so:
<input type="text" name="value" onclick="myFunction()" />
<script type="text/javascript">
function myFunction() {
document.write("Hello");
console.log("Hello");
}
</script>
Writes stuff directly to the html and console. Hope that gets you started.
Regards,
Andy
I don't know why I am struggling with this. Should I be taking a different approach?
I have a form being generated in vb based off a database and then I am trying simply to make a text-box be disabled unless you check a checkbox.
Here is what I have so far. It needs to be dynamic (what I have commented out).
I can't seem to get it to work. The difficult part is referencing
document.form1.el.id.toString() + "_other".disabled
disabled is a binary property, not an attrbute.
You must use disabled='disabled' or remove the attribute to enable the element. It is not a true/false value.
Here is one way:
http://jsfiddle.net/C2WaU/1/
If I understand you correct, this should work for you:
function enable_text(el) {
var textbox_name = el.id.toString() + "_other";
document.getElementById(textbox_name).disabled =
(el.checked) ? "" : "disabled";
}
A working example: http://jsfiddle.net/ve9Gz/3/
I'm having an impossibly hard time finding out to get the actual DOMElement from a jQuery selector.
Sample Code:
<input type="checkbox" id="bob" />
var checkbox = $("#bob").click(function() { //some code } )
and in another piece of code I'm trying to determine the checked value of the checkbox.
if ( checkbox.eq(0).SomeMethodToGetARealDomElement().checked )
//do something.
And please, I do not want to do:
if ( checkbox.eq(0).is(":checked"))
//do something
That gets me around the checkbox, but other times I've needed the real DOMElement.
You can access the raw DOM element with:
$("table").get(0);
or more simply:
$("table")[0];
There isn't actually a lot you need this for however (in my experience). Take your checkbox example:
$(":checkbox").click(function() {
if ($(this).is(":checked")) {
// do stuff
}
});
is more "jquery'ish" and (imho) more concise. What if you wanted to number them?
$(":checkbox").each(function(i, elem) {
$(elem).data("index", i);
});
$(":checkbox").click(function() {
if ($(this).is(":checked") && $(this).data("index") == 0) {
// do stuff
}
});
Some of these features also help mask differences in browsers too. Some attributes can be different. The classic example is AJAX calls. To do this properly in raw Javascript has about 7 fallback cases for XmlHttpRequest.
Edit: seems I was wrong in assuming you could not get the element. As others have posted here, you can get it with:
$('#element').get(0);
I have verified this actually returns the DOM element that was matched.
I needed to get the element as a string.
jQuery("#bob").get(0).outerHTML;
Which will give you something like:
<input type="text" id="bob" value="hello world" />
...as a string rather than a DOM element.
If you need to interact directly with the DOM element, why not just use document.getElementById since, if you are trying to interact with a specific element you will probably know the id, as assuming that the classname is on only one element or some other option tends to be risky.
But, I tend to agree with the others, that in most cases you should learn to do what you need using what jQuery gives you, as it is very flexible.
UPDATE: Based on a comment:
Here is a post with a nice explanation: http://www.mail-archive.com/jquery-en#googlegroups.com/msg04461.html
$(this).attr("checked") ? $(this).val() : 0
This will return the value if it's checked, or 0 if it's not.
$(this).val() is just reaching into the dom and getting the attribute "value" of the element, whether or not it's checked.