Javascript change font color onclick - javascript

So I'm trying to change the font color of my entire page when I click on a radio button, like so:
<input type="radio" name="textcol" value="#FOF8FF" onclick = "changeText('#FOF8FF');"> Alice Blue<br>
Which then calls this function:
function changeText(col)
{
console.log(col);
console.log(document.getElementsByName('boyo'));
var abc = document.getElementsByName('boyo');
for(var i = 0, length = abc.length; i < length; i++)
{
abc[i].style.color = col;
}
}
And just so you're aware, within all my h3 and p tags (the only text within my document), I give them a name "boyo", like this:
<h3 name = "boyo">My favorite food</h3>
But for some reason, it does nothing. I know it has the proper elements (I print them out to console as you can see), and no errors occur, but my font color doesn't change. What the hell am I doing wrong?
EDIT: When I compare the value of just the string "#80FF08" to the value I pass (which when printed out is also the exact same), it returns FALSE that they're equal - how could this be? When I manually set the color it works.

Your code would work fine if you change the O to 0 in your color Code #FOF8FF
function changeText(col) {
console.log(col);
console.log(document.getElementsByName('boyo'));
var abc = document.getElementsByName('boyo');
for (var i = 0, length = abc.length; i < length; i++) {
abc[i].style.color = col;
}
}
<input type="radio" name="textcol" value="#FOF8FF" onclick='changeText("#F0F8FF")'>Alice Blue
<br>
<h3 id="colorMe" name="boyo">My favorite food</h3>

Its because #FOF8FF does not exist, try using #000 or any other color in place of #FOF8FF.
If you want to be clear more about it and inspect your element and try to give color: #FOF8FF, It want work either. For your reference I am attaching screen shot of this.

Change the color to other color working correct, seems like #FOF8FF is not a valid HEX value :
function changeText(color) {
console.log(color);
console.log(document.getElementsByName('boyo'));
var abc = document.getElementsByName('boyo');
for (var i = 0, length = abc.length; i < length; i++) {
abc[i].style.color = color;
}
}
<input type="radio" name="textcol" value="#FOF8FF" onclick="changeText('#33ccff');">Alice Blue
<br>
<h3 name="boyo">My favorite food</h3>

#FOF8FF doesn't exists change to O to 0 and i added different color code and it's working fine
function changeText(col)
{
console.log(col);
console.log(document.getElementsByName('boyo')[0]);
var abc = document.getElementsByName('boyo')[0].style.color = col;
}
<h3 name = "boyo">My favorite food</h3>
<input type="radio" name="textcol" value="#d2d2d2" onclick = "changeText('#d2d2d2');"> Alice Blue<br>

Related

How do I use getElementById on dynamically created inputs?

I'm having a some trouble getting the state of dynamically created checkboxes. I used the code below to add several checkboxes, with dynamic Id's, to the body.
var html = ...;
for(var i = 0; i < options.checkTextArray.length; i++)
{
html +=
`
<label class="checkbox" [attr.for]="'myCheckboxId' + i">
<input class="checkbox__input" type="checkbox" [name]="'myCheckboxName' + i" [id]="'myCheckboxId' + i">
<div class="checkbox__box"></div>${options.checkTextArray[i]}:
</label>
<br>
`;
}
In another part of the code, I would like to get and/or set the state of the checkboxes but havent succeeded so far. I tried using the code below to achieve my goals, but "document.getElementById(...)" keeps returning "null".
var ckbStateBuffer = new Array();
var txtContenBuffer = new Array();
for(var i = 0; i < options.checkTextArray.length; i++) {
ckbStateBuffer.push(document.getElementById("'myCheckboxId' + i").checked);
}
As you can see, I'd like to save the checkbox states in an array and use it, to reset the new states to the old ones (for example when a button is pushed).
So how should I be adding the states to this buffer array? What am I doing wrong in the code above? Tried several other things but none of those worked.
It looks like you just have a simple error in your code. What you're trying to do is something to the affect of:
id=myCheckboxName1
id=myCheckboxName2
id=myCheckboxName3
...
However, your code is not correct:
<input class="checkbox__input" type="checkbox" [name]="'myCheckboxName' + i" [id]="'myCheckboxId' + i">
It's interpreting the entire id as a string and not inserting the numeric value so it looks like this: myCheckboxIdi
Perhaps try the following:
var html = ...;
for(var i = 0; i < options.checkTextArray.length; i++)
{
var checkboxId = `myCheckboxId${i}`;
html +=
`
<label class="checkbox" [attr.for]=${checkboxId}>
<input class="checkbox__input" type="checkbox" [name]=${checkboxId} [id]=${checkboxId}>
<div class="checkbox__box"></div>${options.checkTextArray[i]}:
</label>
<br>
`;
}
Notice how the value is now inserted in the string via the template string? This should work, but I didn't run it so it may need some modification. Your new code for accessing would be something like:
var ckbStateBuffer = new Array();
var txtContenBuffer = new Array();
for(var i = 0; i < options.checkTextArray.length; i++) {
ckbStateBuffer.push(document.getElementById(`myCheckboxId${i}`).checked);
}
Something to this affect should fix your code. Let me know if you need more clarification.
Okay so I found a solution. Apparently you can't use getElementById(checkboxId) to get the checkbox states. You have to create an array using getElementsByTagName("input") and afterwards itterate through this array while checking for inputs of the checkbox type.
var inputsArray = document.getElementsByTagName("input");
var ckbStateBuffer = new Array();
for (var i = 0; i < 3; i++)
{
if(inputsArray[i].type == "checkbox")
{
ckbStateBuffer.push(inputsArray[i].checked);
}
}
JSFiddle here: https://jsfiddle.net/Maximo40000/agL9opq6/
A big thanks to Jarred Parr!

Uncaught TypeError: Cannot set property 'innerHTML' of null error

I got error of Uncaught TypeError: Cannot set property 'innerHTML' of null for below script.
I added the script tags after the body. But still I get the error.
I want to show the text boxes in the same page within the div with the ID showTextBoxes.
Below is the HTML and JS.
function showArray(){
var numofArr = document.getElementById("numofArr").value;
for (let i = 0; i < numofArr; i++) {
var a = document.writeln('<input type="text" name="Fname"><br/><br/>');
document.getElementById('showTextBoxes').innerHTML = a;
}
document.writeln('<input type="submit" name="submit">');
}
<p>Number of arrays(array within 0-9)</p>
<input type="text" id="numofArr" pattern="[0-9]">
<input type="submit" onclick="showArray()" value="Submit"><br><br>
<div id="showTextBoxes"></div>
Actually document.write()and document.writeln() works in a different ways you think.
It actually clears all the document in your case you you are getting null.
See this
If you wanna add some element to your body you can use document.body.innerHTML += string.appendChild() can also be used but its not for stings
function showArray(){
var numofArr = parseInt(document.getElementById("numofArr").value);
for (let i = 0; i < numofArr; i++) {
var a = '<input type="text" name="Fname" /><br/><br/>'
document.getElementById('showTextBoxes').innerHTML += a;
}
document.body.innerHTML += '<input type="submit" name="submit"/>'
}
<body>
<p>Number of arrays(array within 0-9)</p>
<input type="text" id="numofArr" pattern="[0-9]">
<input type="submit" onclick="showArray()" value="Submit"><br><br>
<div id="showTextBoxes"></div>
I think there are several ways, but I would recommend looking at append. Something like this should work:
function showArray(){
var numofArr = document.getElementById("numofArr").value;
for (let i = 0; i < numofArr; i++) {
var textBox = document.createElement("input");
var enter = document.createElement("br");
document.getElementById('showTextBoxes').append( textBox );
document.getElementById('showTextBoxes').append( enter );
}
}
There are various places in your script which prevent it from running correctly. I'll address them step by step so you can follow along.
First of all, you should avoid inline event handlers in your HTML for the same reasons you should avoid inline style declarations. So don't use onclick=" ... " inside your HTML and instead add eventlisteners in your JS. This also gives you the ability to cancel the default behaviour or stop event propagation and such things.
Next thing is, you try to use the value of your numofArr input as upper bounds for your loop without casting it to a Number. Because <input> elements return their value as a String, this is very likely to fail. Besides, you should use the type="number" attribute instead of type="text" on that element. It's not required to do so, but just good measure.
OK, now for the showArray function:
Instead of using document.writeln (or document.write), create elements with document.createElement and add them to the DOM with appendChild.
You can see a working example below. Don't be confused by the byId and makeEl functions, they are just utilities so you don't have to write document.getElementById and document.createElement all the time.
// ====== UTILITY FUNCTIONS ======
function byId (id, root = document) {
return root.getElementById(id);
}
function makeEl (tag) {
return document.createElement(tag);
}
// ====== PROGRAM STUFF ======
function showArray (e) {
e.preventDefault();
let numofArr = parseInt(byId('numofArr').value, 10);
let output = byId('showTextBoxes');
for (let i = 0; i < numofArr; i++) {
let textIn = makeEl('input');
textIn.type = 'text';
textIn.name = 'Fname';
output.appendChild(textIn);
output.appendChild(makeEl('br'));
output.appendChild(makeEl('br'));
}
let submit2 = makeEl('input');
submit2.type = 'submit';
submit2.value = 'Submit';
document.body.appendChild(submit2);
}
byId('submit1').addEventListener('click', showArray, false);
<p>Number of arrays(array within 0-9)</p>
<input type="number" id="numofArr">
<input id="submit1" type="submit" value="Submit"><br><br>
<div id="showTextBoxes"></div>

Set an array of the checkbox values with another array of values

I have a set of input checkboxes on a form that look like this:
<input type="checkbox" value=""><span value="Atlanta">Atlanta</span>
<input type="checkbox" value=""><span value="Charleston">Charleston</span>
<input type="checkbox" value=""><span value="Chicago">Chicago</span> and etc.
The above is due to running this, $dataTable.ajax.reload(), and for some reason this erases the values of the checkboxes in my form. These checkboxes are not hardcoded and are being dynamically generating.
Instead of doing the below, I realize I can just refresh the page and get all the value back, but I'd like to see if there is another way to do what I'm trying to do below.
Anywho, I took the span text of each checkbox, turned that into an array and called it spanarr. I also turned the input checkboxes into an array, called emergcheck.
var emergspanarr = $('#emergencyForm span').toArray();
var spanarr = [];
var emergcheck = $('#emergencyForm input[type="checkbox"]');
emergspanarr.map(function(item){
spanarr.push(item.innerHTML.trim());
});
I'm trying to insert one span value (from spanarr) into each of input checkbox (from emergcheck).
What I have so far:
for (var j = 0; j < emergcheck.length; j++){
for (var k = 0; k < spanarr.length; k++){
emergcheck.attr("value", function(i, val){
return val + spanarr[k];
})
}
}
But it's producing this:
<input value="AtlantaCharlestonChicagoHouston (Sales)Houston (Terminal)Long BeachMarseillesMiamiMontreal....Santa Ana SavannahSeattleSecaucusTorontoVancouverAtlantaCharlestonChicagoHouston (Sales)Houston (Terminal)Long BeachMarseillesMiamiMontrealSanta Ana .....Santa AnaSavannahSeattleSecaucusTorontoVancouver" type="checkbox"><span value="Atlanta">Atlanta</span>
<input value="AtlantaCharlestonChicagoHouston (Sales)Houston (Terminal)Long BeachMarseillesMiamiMontreal....Santa Ana SavannahSeattleSecaucusTorontoVancouverAtlantaCharlestonChicagoHouston (Sales)Houston (Terminal)Long BeachMarseillesMiamiMontrealSanta Ana .....Santa AnaSavannahSeattleSecaucusTorontoVancouver" type="checkbox"><span value="Charleston">Charleston</span> and etc.
I want it to be this instead:
<input type="checkbox" value="Atlanta"><span value="Atlanta">Atlanta</span>
<input type="checkbox" value="Charleston"><span value="Charleston">Charleston</span>
<input type="checkbox" value="Chicago"><span value="Chicago">Chicago</span
I feel like I am close. What am I missing? In need of another pair of eyes. Thanks,
Just try to change code with below code -
JS Code -
for (var j = 0; j < emergcheck.length; j++){
emergcheck.eq(j).val(spanarr[j]);
}
Maybe it can help you.
I think you just want the value of the input. You can use .val() from jQuery or just .value as pure js.
jQuery way:
var emergspanarr = $('#emergencyForm span').toArray();
var emergcheck = $('#emergencyForm input[type="checkbox"]').toArray();
for (var j = 0; j < emergcheck.length; j++) {
emergcheck[j].val(emergspanarr[j].val());
}
Pure js way:
var emergspanarr = $('#emergencyForm span').toArray();
var emergcheck = $('#emergencyForm input[type="checkbox"]').toArray();
for (var j = 0; j < emergcheck.length; j++){
emergcheck[j].value = emergspanarr[j].value;
}

Store values from dynamically generated text boxes into array

I'm creating a Time table generating website as a part of my project and I am stuck at one point.
Using for loop, I am generating user selected text boxes for subjects and faculties. Now the problem is that I cannot get the values of those dynamically generated text boxes. I want to get the values and store it into array so that I can then later on store it to database
If I am using localstorage, then it sometimes shows NaN or undefined. Please help me out.
Following is my Jquery code
$.fn.CreateDynamicTextBoxes = function()
{
$('#DynamicTextBoxContainer, #DynamicTextBoxContainer2').css('display','block');
InputtedValue = $('#SemesterSubjectsSelection').val();
SubjectsNames = [];
for (i = 0; i < InputtedValue; i++)
{
TextBoxContainer1 = $('#DynamicTextBoxContainer');
TextBoxContainer2 = $('#DynamicTextBoxContainer2');
$('<input type="text" class="InputBoxes" id="SubjectTextBoxes'+i+'" placeholder="Subject '+i+' Name" style="margin:5px;" value=""><br>').appendTo(TextBoxContainer1);
$('<input type="text" class="InputBoxes" id="FacultyTextBoxes'+i+'" placeholder="Subject '+i+' Faculty Name" style="margin:5px;" value=""><br>').appendTo(TextBoxContainer2);
SubjectsNames['SubjectTextBoxes'+i];
}
$('#DynamicTextBoxContainer, #UnusedContainer, #DynamicTextBoxContainer2').css('border-top','1px solid #DDD');
}
$.fn.CreateTimeTable = function()
{
for (x = 0; x < i; x++)
{
localStorage.setItem("Main"+x, +SubjectsNames[i]);
}
}
I am also posting screenshot for better understanding
I understand you create 2 text boxes for each subject, one for subject, and second one for faculty. And you want it as a jQuery plugin.
First of all, I think you should create single plugin instead of two, and expose what you need from the plugin.
You should avoid global variables, right now you have InputtedValue, i, SubjectsNames, etc. declared as a global variables, and I believe you should not do that, but keep these variables inside you plugin and expose only what you really need.
You declare your SubjectNames, but later in first for loop you try to access its properties, and actually do nothing with this. In second for loop you try to access it as an array, but it's empty, as you did not assign any values in it.
Take a look at the snippet I created. I do not play much with jQuery, and especially with custom plugins, so the code is not perfect and can be optimized, but I believe it shows the idea. I pass some selectors as in configuration object to make it more reusable. I added 2 buttons to make it more "playable", but you can change it as you prefer. Prepare button creates your dynamic text boxes, and button Generate takes their values and "print" them in result div. generate method is exposed from the plugin to take the values outside the plugin, so you can do it whatever you want with them (e.g. store them in local storage).
$(function() {
$.fn.timeTables = function(config) {
// prepare variables with jQuery objects, based on selectors provided in config object
var numberOfSubjectsTextBox = $(config.numberOfSubjects);
var subjectsDiv = $(config.subjects);
var facultiesDiv = $(config.faculties);
var prepareButton = $(config.prepareButton);
var numberOfSubjects = 0;
prepareButton.click(function() {
// read number of subjects from the textbox - some validation should be added here
numberOfSubjects = +numberOfSubjectsTextBox.val();
// clear subjects and faculties div from any text boxes there
subjectsDiv.empty();
facultiesDiv.empty();
// create new text boxes for each subject and append them to proper div
// TODO: these inputs could be stored in arrays and used later
for (var i = 0; i < numberOfSubjects; i++) {
$('<input type="text" placeholder="Subject ' + i + '" />').appendTo(subjectsDiv);
$('<input type="text" placeholder="Faculty ' + i + '" />').appendTo(facultiesDiv);
}
});
function generate() {
// prepare result array
var result = [];
// get all text boxes from subjects and faculties divs
var subjectTextBoxes = subjectsDiv.find('input');
var facultiesTextBoxes = facultiesDiv.find('input');
// read subject and faculty for each subject - numberOfSubjects variable stores proper value
for (var i = 0; i < numberOfSubjects; i++) {
result.push({
subject: $(subjectTextBoxes[i]).val(),
faculty: $(facultiesTextBoxes[i]).val()
});
}
return result;
}
// expose generate function outside the plugin
return {
generate: generate
};
};
var tt = $('#container').timeTables({
numberOfSubjects: '#numberOfSubjects',
subjects: '#subjects',
faculties: '#faculties',
prepareButton: '#prepare'
});
$('#generate').click(function() {
// generate result and 'print' it to result div
var times = tt.generate();
var result = $('#result');
result.empty();
for (var i = 0; i < times.length; i++) {
$('<div>' + times[i].subject + ': ' + times[i].faculty + '</div>').appendTo(result);
}
});
});
#content div {
float: left;
}
#content div input {
display: block;
}
#footer {
clear: both;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="container">
<div id="header">
<input type="text" id="numberOfSubjects" placeholder="Number of subjects" />
<button id="prepare">
Prepare
</button>
</div>
<div id="content">
<div id="subjects">
</div>
<div id="faculties">
</div>
</div>
</div>
<div id="footer">
<button id="generate">Generate</button>
<div id="result">
</div>
</div>

how can I call tab key event in javascript

Here is my simple data
John Smith Individual 010987654
I have three textboxes and the above data will automatically insert in the first textbox of my web page.
My problem is
How can I make as soon as data is inserted in the textbox (means when textbox’s onchange event is fired)
First, javascript will find ‘tab’ space in this string
Second, if find ‘tab’ space in the string, javascript will press ‘tab’ key and insert data in the another text box.
Here's a plain old DOM-0 JavaScript solution, just for fun.
document.getElementById('the_form').onchange = function() {
var field = this[0];
var parts = field.value.split('\t');
for (var i = 0; field = this[i]; i++) {
field.value = parts[i] || '';
}
}
http://jsfiddle.net/vKaxP/
I thought you want to split those texts into different textboxes, so I got something like:
$("#a").change(function(){
var s = $(this).val();
if (s.match(/\t+/)) {
var a = s.split(/\t+/);
$('#a').val(a[0]);
$('#b').val(a[1]);
$('#c').val(a[2]);
}
});
if you type a b c into the first input box, press tab or enter, b and c would appear into other textboxes, repectively.
I use \s(space) for test in jsfiddle. You could just change it to \t for tab.
Here is prototype of what you need to do.
HTML:
<div>
<input id="a" />
</div>
<div>
<input id="b" />
</div>
JavaScript:
$('#a').on('change', function () {
var value = $(this).val();
// Test if string has a tab:
if (/\t/.test(value)) {
// Just set the value of the other text box
// And set focus:
// Using jQuery that would be:
$('#b').val(value).focus();
}
});
Working demo: http://jsfiddle.net/tkirda/XmArP/
If I correctly understand the question as "The server puts all the data into one field, tab separated, and I want to split it up into several textfields", then try this:
On load:
var fields = [$("#firstField"), $("#secondField"), $("#thirdField")];
var data = fields[0].val().split(/\t/);
for (var i = 0; i < 3; i++) {
fields[i].val(data[i]);
}

Categories

Resources