How do I use window.find to change css style? - javascript

Through a combination of AJAX and PHP, I put some text data in a span at the bottom of the page. Now I want to search this text for a string. My page is full of checkboxes, and their values are the strings I will search for.
Goal: Using a loop, cycle through the values of all checkboxes on the page. Search the page for each checkbox's value (ideally, within the text in the AJAX-informed span). If the checkboxes value is found, change that checkboxes CSS style color.
My code so far: I have a form full of checkboxes all named "comment" each with unique IDs:
<input type="checkbox" name="comment" id="hjl1" value="the comment."
onclick="createOrder()"><label for="hjl1" onclick="createOrder()"
title="comment"> onscreen text for this checkbox </label>
When triggered , using Javascript, I go through every checkbox in that form.
var comment=document.forms[0].comment;
var txt="";
var ii;
for (ii=0;ii<comment.length;ii++)
{str=comment[ii].value;}
Now I want to insert window.find in that loop to check if that value is on my page.
if (window.find) {
var found = window.find (str);
if (!found) {
document.getElementById("?????").style["color"] = "red";
}
}
The idea is that when the checkbox is checked, the javascript would search for the value "the comment." on page. If found, the checkbox label will add the CSS style color red.
Somehow, I want to combine these ideas, but there are so many problems. How do I get the element by ID in this loop? Can window.find search the text created by php in my span?
Would it be better to not use window.find at all?
var source = document.getElementsByTagName('html')[0].innerHTML;
var found = source.search("searchString");
I'm so confused and new. Please be patient. Thank you for reading this far.

I misunderstood at first, and wrote code to highlight text within the page.
Yes, window.find is fine to use for this as you only need to know if the value exists or not. It might behave a bit odd (scroll to bottom) when used in frames though.
Also, I added a function for your onClick, but I'm not sure if this is wanted. It will change color of the label if text if found when clicked (also).
Below is a small example:
function checkThis(ele) {
var str = ele.value;
if (window.find) {
var found = window.find(str);
if (found) {
var id = ele.getAttribute('id');
var lbl = document.querySelectorAll('label[for="' + id + '"]');
if (lbl) lbl[0].style.color = "red";
}
}
}
window.onload = function() {
var comment = document.form1.getElementsByTagName('input');
for (var x = 0; x < comment.length; x++) {
if (comment[x].type == 'checkbox') {
var str = comment[x].value;
if (window.find) {
var found = window.find(str);
if (found) {
var id = comment[x].getAttribute('id');
var lbl = document.querySelectorAll('label[for="' + id + '"]');
if (lbl) lbl[0].style.color = "red";
}
}
}
}
}
<form name="form1">
<input type="checkbox" name="comment" id="hjl1" value="the comment." onclick="checkThis(this);" />
<label for="hjl1" onclick="createOrder()" title="comment">onscreen text for this checkbox</label>
<input type="checkbox" name="comment" id="hjl2" value="the comment2." onclick="checkThis(this);" />
<label for="hjl2" onclick="createOrder()" title="comment">onscreen text for this checkbox</label>
<br/>
<b>first comment.</b><br/>
<b>other comment.</b><br/>
<b>some comment.</b><br/>
<b>the comment.</b><br/>
<b>whatever comment.</b><br/>
<b>not this comment.</b><br/>
</form>

try this as your function code
function loopy() {
var comment=document.forms[0].comment;
var txt="";
var ii;
for (ii=0;ii<comment.length;ii++) {
if (comment[ii].checked) {
str=comment[ii].value;
id = comment[ii].id;
nextLabelId = comment[ii].nextSibling.id;
if (window.find) { // Firefox, Google Chrome, Safari
var found = window.find (str);
if (found == true) {
// found string
//comment[ii].style['outline']='1px solid red';
document.getElementById(nextLabelId).className = 'selected';
}
} else {
// this browser does not support find()
alert('not supported');
}
}
}
}
So, in order to get the checkbox id, you just add id = comment[ii].id in your loop.
To change the color, it's best to use class name and use styling in the css file. so if you want to change the label that is after the checkbox to red you will first find the label's id using nextSiblings and then add the .selected class name. Just remember that you need to remove the coloring if the user un-check the box
Regarding the usage of find(), not supported by all browser so this could be an issue and also not sure it will be able to find on the content you injected to the DOM by AJAX so this needs some testing.
I would suggest moving this code to jQuery as some features seems to be easier using their functionality.

Related

javascript/html - change color of checkbox text when box if checked by user

I'm trying to change the color of my checkbox text label when the user checks the box and clicks the toggle button. I looked up other examples and tried to make my own solution below but it doesn't work when I check the boxes I want to check and click the button. I was wondering why?
function addItem() {
var input = document.getElementById("textbox");
var wrapper = document.getElementById("checklist_items");
if (input.value.trim() != "") {
var new_element = document.createElement("DIV");
new_element.innerHTML = '<input type="checkbox"> ' + input.value;
wrapper.appendChild(new_element);
document.getElementById('textbox').value = '';
} else {
alert("You must enter at least 1 character.");
}
}
function toggleItem() {
var chkbx = document.querySelectorAll('checklist_items');
if (chkbx.checked) {
document.getElementById('checklist_items').style.color = "red";
} else {
document.getElementById("checklist_items").style.backgroundColor = "transparent";
}
}
<html>
<head>
<title>Checklist</title>
</head>
<body>
<div><h1>My to-do list</h1></div><br />
<div id ="myCheckList">Enter an item:</div>
<div>Type something: <input type="text" id="textbox"></input></div>
<input type="button" id="addBut" value = "Add item" onclick="addItem()"/>
<input type="button" id="toggleBut" value = "Toggle highlight" onclick="toggleItem()"/>
<script src="addHandler.js"></script>
<div id="checklist_items"></div>
</body>
</html>
How my program works is the user enters a bunch of text in the textbox and clicks the add button, which creates a checkbox for their input. I want the name of their input beside the checkbox to change colors when I check it and click the toggle button.
var chkbx = document.querySelectorAll('checklist_items') needs to be var chkbx = document.querySelectorAll('#checklist_items') or var chkbx = document.getElementById('checklist_items').
querySelectorAll takes CSS selectors as arguments, which are either html elements or class or id names with the corresponding prefix. IDs have the prefix # and classes have the prefix .
Using JQuery:
$(".your_checkbox_class").change(function () {
if ($(this).is(':checked')) {
$(this).css("background-color","your_color_here");
}
};
EDIT:
You should also give this checkbox class or id
EDIT 2:
document.getElementById('checklist_items').style.color = "red";
means that font color will change but checkbox has no text

getting the value of a textbox when user enters the name/id of the field

Using jquery to get the value of a textbox.
BUT
i need to enter the id of the textbox, then use that value to get the value of the textbox using jquery.
var tt = $("#fieldname").val()
that works
now how do i enter the fieldname at runtime, and get jquery to execute the val command as if it was hard coded?
There are a few ways that you could do this. One way is to listen to one of the keyboard or change events on the textbox you enter the id into, to help determine when the input has changed. So for example
$("#inputText").on("keyup", function(keyupEvent){
var textboxId = $("#inputText").val();
var textboxIdValue = $("#" + textboxId).val();
});
Or another way could be to use a click event with similar kind of logic, so for example
$("#clickMe").on("click", function(){
var textboxId = $("#inputText").val();
var textboxIdValue = $("#" + textboxId).val();
})
An example for the use case of both can be seen here https://fiddle.jshell.net/xpvt214o/114584/
Here is an example for you to get started with:
<body>
<p>Type "one" or "two" below</p>
<input id="search" />
<input id="one" value="This input is #one" />
<input id="two" value="And this is #two" />
<p id="result">No input specified</p>
</body>
And the corresponding jQuery code:
// Cache jQuery elements for performance and readability
var $search = $("#search");
var $result = $("#result");
$search.on("change", function() {
var search_value = $search.val();
if (search_value.length) {
search_value = "#" + search_value.toLowerCase().trim(); // Sanitise user input
if ($(search_value).length) {
$result.text($(search_value).val());
} else {
$result.text("Input not found");
}
} else {
$result.text("No input specified");
}
});
This will show the value of the specified input, if it exists.
You can see it in action here: https://jsfiddle.net/jeevantakhar/xpvt214o/114558/

How can I change the label for css style?

I have a checkbox with label.
<input type="checkbox" name="comment" id="abc1" value="the value."
onclick="createOrder()"><label for="abc1" onclick="createOrder()"
title="title"> onscreen text for this checkbox </label>
In a javascript function, I want to change the appearance of the input. Here is an example that works (changes the element's visibility) but is not what I want to do:
if (n !== -1) {
document.getElementById(id).style.visibility = "hidden";
}
However, I don't want to make it invisible. I want to change the text color of the words associated with the checkbox ("onscreen text for this checkbox") The text would change from the default black to grey.
I don't know how to change the "label for" style. Can anyone help change the javascript? The result would simply change the color of the text.
As you said the code you're trying works so to target next node, you can use .nextSibling
if (n !== -1) {
document.getElementById(id).nextSibling.style.color= "#c8c8c8"; //color you need"
}
else{
document.getElementById(id).nextSibling.style.color= "#fefefe"; //Default color
}
You can do something like using jQuery:
jQuery:
$(document).ready(function(ee){
$("#abc1").click(function(){
if ($(this).is(':checked')) {
$(this).next().css({"color": "Red"});
}else
{
$(this).next().css({"color": "black"});
}
});
});
HTML:
<input type="checkbox" name="comment" id="abc1" value="the value." ><label for="abc1" title="title"> onscreen text for this checkbox </label>
This should work.
Thanks
it can easily be achieved, doesnt matter where the label is located or how many are there.
there is an answer Here that shows how to get elements by their attributes.
lets take the function from that answer, adjust it and use it for your question:
//get all labels with for=abc1 attribute
el=getLabelByForAttribute("abc1");
//loop through those labels and change their style
el.forEach(function(elem,idx){
elem.style["color"]="grey";
});
function getLabelByForAttribute(a)
{
var matchingElements = [];
//get all labels in the document
var allElements = document.getElementsByTagName('label');
for (var i = 0, n = allElements.length; i < n; i++)
{
//if those labels have the required 'for' attribute
if (allElements[i].getAttribute("for") ==a)
{
// Element exists with attribute. Add to array.
matchingElements.push(allElements[i]);
}
}
return matchingElements;
}
<input type="checkbox" name="comment" id="abc1" value="the value." onclick="createOrder()">
<label for="abc1" onclick="createOrder()" title="title">onscreen text for this checkbox</label>

How to get the innerHTML of an input control including the values?

I have a div, its called tab1. Inside the tab1 div are many inputs (fields and radio buttons). I am getting the innerHTML like this:
document.getElementById("tab1").innerHTML;
Example code:
<div id="tab1">
<input type="text" id="text1" />
</div>
That works, but if I entered any value into a text1 input for example, its not in the innerHTML. How would I get the innerHTML including the entered values? Is that possible at all?
Thanks!
<div id="tab1">
<input type="text" id="text1"
onkeyup="javascript:this.setAttribute("value", this.value);"/>
</div>
This will gives the values with div's innerHTML.
document.getElementById("tab1").innerHTML;
You can change the event accordingly, I set it onKeyUp.
If you want to get the values of inputs/radios, you can do it with jQuery:
var Inputs = $("div#tab1 input, div#tab1 radio");
You now have an array of all input and radios in the variable Inputs. You can then access the values like this: Inputs[0].value
If you want to use plain JavaScript that could look like this:
var Inputs = document.getElementById("tab1").getElementsByTagName('input');
You can now access them like:Inputs[0].valueandRadios[0].value`
#edit
Thanks, I corrected these mistakes.
If you type something in the textbox, what does the innerHTML look like? Does it look like
<input type="text" id="text1" value="your_value" />?
If so, here is a simple function that returns what you want:
function getInnerHtml() {
var div = document.getElementById("tab1");
var childNodes = div.childNodes;
var innerHtml = "";
for (var i = 0; i < childNodes.length; i++) {
var node = childNodes[i];
if (node.nodeType == 1) {
if (node.getAttribute("type") == "text") {
if (node.value != "") {
//! This will change the original outerHTML of the textbox
//If you don't want to change it, you can get outerHTML first, and replace it with "value='your_value'"
node.setAttribute("value", node.value);
}
innerHtml += node.outerHTML;
} else if (node.getAttribute("type") == "radio") {
innerHtml += node.outerHTML;
}
}
}
}
Hope it's helpful.

Javascript calculator as users type numbers

I'm a noob at Javascript, but I'm trying to implement something on my website where users can type a quantity, and the subtotal updates dynamically as they type.
For example: if items are 10 dollars each, and a user types 5 in the text field I would like it to show $50 next to the text box. Pretty simple multiplication, but I don't know how to do it with Javascript. I think onKeyPress somehow? Thanks!
Assuming the following HTML:
<input type="text" id="numberField"/>
<span id="result"></span>
JavaScript:
window.onload = function() {
var base = 10;
var numberField = document.getElementById('numberField');
numberField.onkeyup = numberField.onpaste = function() {
if(this.value.length == 0) {
document.getElementById('result').innerHTML = '';
return;
}
var number = parseInt(this.value);
if(isNaN(number)) return;
document.getElementById('result').innerHTML = number * base;
};
numberField.onkeyup(); //could just as easily have been onpaste();
};
Here's a working example.
You should handle 'onkeyup' and 'onpaste' events to ensure you capture changes by keyboard and via clipboard paste events.
<input id='myinput' />
<script>
var myinput = document.getElementById('myinput');
function changeHandler() {
// here, you can access the input value with 'myinput.value' or 'this.value'
}
myinput.onkeyup = myinput.onpaste = changeHandler;
</script>
Similarly, use getElementById and the element's innerHTML attribute to set the contents of an element when you want to show the result.

Categories

Resources