I am new with javascript and I have one question now. how can we refer to one function by using Radio button? I have list of countries and this list includes of population and area and density. I want to add radio button to my script when I select for example radio button "area" this function comes back to another function and extract the area of countries from the other function. I have written these functions but it works only for area. I need to add 3 radio button to this script
when I select for example the density button it refers to this function and extract the density of these countries and then the second function will change the colour. please help me
var myCantons = [];
myCantons[0] = ["Name Country","area kmĀ²","density",Population];
myCantons[102] = ["Germany",221.90,2696,117];
myCantons[106] = ["Italy",271.50,6510,485];
myCantons[107] = ["Denmark",141.31,2661,406];
myCantons[122] = ["Poland",286.25,3331,237];
myCantons[130] = ["Russia",124.49,5099,431];
function myInit(){
for(var i = 100; i < myCantons.length; i++){
if(typeof myCantons[i] != 'undefined'){
var myDensity = myCantons[i][2] ;
var myNewColor = '';
if(myDensity < 110){
myNewColor = 'yellow';
} else if (myDensity > 250){
myNewColor = 'red';
} else {
myNewColor = 'orange';
}
var mySvgId ='myCantonId'+(''+i).substr(1);
document.getElementById(mySvgId).setAttributeNS(null,'fill',myNewColor);
}
}
}
You might want to look into DOM events.
var handleChange = function (e) {
if(e.target.checked) {
// do something if the checkbox was selected
} else {
// do something if the checkbox was deselected
}
}
document.getElementById("myCheckbox").addEventlistener("change", handleChange, false);
You can attach a change event to any input element and monitor it's state. For checkboxes/radio buttons that would be the checked property. It is true if the input is selected.
We can put three radio buttons
<input type="radio" name="group1" id="area" value="area" onClick="myInit(this)"/>
<input type="radio" name="group1" id="density" value="density" onClick="myInit(this)" />
<input type="radio" name="group1" id="population" value="population" onClick="myInit(this)"/>
myInit function would be modified as follows to take argument of radio button object.
myInit(myradio)
{
if(myradio.checked == true && myradio.value=='area')
//Here logic for returning area will come
else if(myradio.checked == true && myradio.value=='density')
//Here logic for returning density will come
else if(myradio.checked == true && myradio.value=='population')
//Here logic for returning population will come
}
Related
I'm trying to check whether the length of characters typed into the text box is less than 6, and if it is, I want its background to be red. Unfortunately, I can't seem to figure out where I'm going wrong with this simple problem.
var textBox = getElementsByName('random');
function checkLength() {
if (textBox.value.length < 6) {
textBox.style.backgroundColor = "red";
}
}
<input type="text" name="random" onfocus="checkLength();">
A few issues in your code:
you need to put <script> code at the end, so that DOM is loaded and ready before you access elements in it.
getElementsByName('random') needs to document.getElementsByName('random'), which will actually return a list so you need to get first element from the list.
Also logically, you need to remove the red background once the text
length in input exceeds 6 and it would be better if you attach function to oninput event.
<input type="text" name="random" oninput="checkLength();">
<script type="text/javascript">
var textBox = document.getElementsByName('random')[0];
function checkLength() {
if (textBox.value.length < 6) {
textBox.style.backgroundColor = "red";
} else {
textBox.style.backgroundColor = "white";
}
}
</script>
When the page first loads, the element with a name of random doesn't exist.
You will need to initialise your textBox global after the page loads.
You can do this by replacing
var textBox = document.getElementsByName("random")[0]
with
var textBox;
window.onload = function() {
textBox = document.getElementsByName("random")[0]
}
Try this
// add an id of "random" to your input
function checkLength() {
const textBox = document.getElementById("random")
if (textBox.value.length < 6) {
textBox.style.backgroundColor = "red";
} else {
textBox.style.backgroundColor = "white";
}
}
Working example: http://jsbin.com/caseqekusi/1/edit?html,js,output
Note: If you want the box to be red right away, you'll have to modify it a bit, let me know if you have questions.
I would suggest to use oninput as well, so it updates as you type and marks the field as "valid" as soon as you have reached a certain length.
You could also get rid of var textbox = ... by using document.activeElement. It makes your function reusable for other input fields. And it no longer matters when your code is loaded.
function checkLength() {
// Get current focused element
const textBox = document.activeElement;
if ( !textBox.value || textBox.value.length < 6 ) {
textBox.style.backgroundColor = "red";
}
else {
textBox.style.backgroundColor = "#fff";
}
}
<input type="text" name="random" onfocus="checkLength()" oninput="checkLength()">
I have a jsp page on which table is coming dynamically and have checkboxes on that page when you click on that box it should save in array and when it uncheck the box it should remove value from array.
I have tried this by creating a method but it is not working perfectly can you please help me..
function addCheckboxVAlues(checked){
var split = checked.value.split("|");
var key =split[0];
var value=split[1];
var chks = $("input[name='"+key+"']:checked");
if (chks.length > 0) {
uninvoiced.push(value);
} else {
uninvoiced.pop(key);
}
console.log(uninvoiced);
}
You need to use splice to remove the element from the array
function addCheckboxVAlues(checked){
var split = checked.value.split("|");
var key =split[0];
var value=split[1];
var chks = $("input[name='"+key+"']:checked");
var index = uninvoiced.indexOf(key);
if (chks.length > 0) {
uninvoiced.push(value);
} else if(index > -1){
uninvoiced.splice(index, 1);
}
console.log(uninvoiced);
}
This code looks way more complex than it needs to be. Presumably the checkbox has a click listener on it, so it should be called with the checkbox as this. All you have to do is add the value if the checkbox is checked, or remove it if it's unchecked.
That will be hugely more efficient than running a checked selector every time.
The following uses an inline listener for convenience, likey you're attaching them dynamically but it seems to be called the same way.
var uninvoiced = [];
function addCheckbox(el) {
var value = el.value.split('|')[1];
if (el.checked) {
uninvoiced.push(value);
} else {
uninvoiced.splice(uninvoiced.indexOf(value), 1);
}
console.log(uninvoiced);
}
foo|bar: <input type="checkbox" value="foo|bar" onclick="addCheckbox(this)">
fee|fum: <input type="checkbox" value="fee|fum" onclick="addCheckbox(this)">
There is a polyfill for indexOf on MDN.
I'm getting close to desperate here but I can't seem to find any solution to this. I basically have a problem with a click event that somehow acts as a drag event. Which is odd because, as far as I can tell, it really shouldn't.
Let me explain what's what. I have these simple radio buttons:
<div class="fruitButtons">
<input type="radio" name="radio" id="Apple">
<label for="Apple">Apple</label>
<input type="radio" name="radio" id="Banana">
<label for="Banana">Banana</label>
<input type="radio" name="radio" id="Citron">
<label for="Citron">Citron</label>
</div>
<br><b>selected:</b>
<div class="status">none</div>
I use jQuery UI to transform these regular buttons into a nice looking buttonset via $(".fruitButtons").buttonset();.
Now I need the possibility to reset the buttonset, i.e. to uncheck all buttons at once. Since I don't want a separate reset button for that, I need the reset to happen when you click on an already checked button. To me, this is the most intuitive way to handle these radio buttons.
This is the (obviously simplified) way it's supposed to work:
$(function() {
$(".fruitButtons").buttonset();
var uncheck = apple = banana = citron = 0;
$(".fruitButtons label").click(function(){
var name = $(this).text();
// see if button was previously checked
// if yes set var 'uncheck' to 1
if ((name == "Apple") && (apple)) uncheck = 1;
if ((name == "Banana") && (banana)) uncheck = 1;
if ((name == "Citron") && (citron)) uncheck = 1;
apple = banana = citron = 0;
if (!uncheck) {
if (name == "Apple") apple = 1;
if (name == "Banana") banana = 1;
if (name == "Citron") citron = 1;
// display name of currently checked button
$(".status").text(name);
}
else {
// unchecking the hidden input element
$(this).prev().prop("checked", false);
// resetting the buttonset to its initial state
$(this).parent().buttonset("refresh");
$(".status").text("none");
uncheck = 0;
}
});
});
Check out the Fiddle: http://jsfiddle.net/6yx0rqjf/6/
But here's the problem: The unchecking process does not work properly. In fact, it only works when you actually drag the mouse while clicking, i.e. if you move the mouse a little while the mouse button is depressed.
Updating the $(".status") part works perfectly every time you click the button, but unchecking it is only succesful if you move the mouse a little.
How is this possible? Is this a bug? I was able to reproduce this behavior on Firefox 40.0.3 and Chrome 45.0.2454.85. I also found this unresolved question that may be somehow related:
jQuery click event only working after moving the mouse in Chrome
So, can anyone help me fix this? Is that even possible?
I think the problem is that you're putting the click handler on the label, not the button itself. I moved it to the button, and adjusted the code, and it works correctly.
$(function() {
var uncheck = apple = banana = citron = 0;
$(".fruitButtons").buttonset();
$(".fruitButtons :radio").click(function(){
var name = $(this).next("label").text();
// see if button was previously checked
// if yes set var 'uncheck' to 1
if ((name == "Apple") && (apple)) uncheck = 1;
if ((name == "Banana") && (banana)) uncheck = 1;
if ((name == "Citron") && (citron)) uncheck = 1;
apple = banana = citron = 0;
if (!uncheck) {
if (name == "Apple") apple = 1;
if (name == "Banana") banana = 1;
if (name == "Citron") citron = 1;
// display name of currently checked button
$(".status").text(name);
}
else {
// unchecking the hidden input element
$(this).prop("checked", false);
// resetting the buttonset to its initial state
$(this).button("refresh");
$(".status").text("none");
uncheck = 0;
}
});
});
FIDDLE
I have a snippet of HTML that is part of a form where there are two input's. Via CSS I have managed to make the label associated with each input to sit inside their corresponding input to act as a placeholder.
Now, with some standard JS (not JQuery I'm afraid), I wanted to capture the event that the user does (i.e. on a mouse click or keyboard press) on the input and dynamically change the look and feel of the label.
http://jsfiddle.net/8nBAQ/2/
The conditions that I need to meet are:
When a user clicks on the input for the first time. The label changes colour to a light grey. After click, if the user then enters a character, the label disappears and the character you have just pressed is displayed instead.
When a user clicks on the input for the first time. The label changes colour to a light grey. After click, if the user then clicks or tabs away from the input, the label changes colour back to it's original state of black.
After entering a few characters into the input, if the user decides to delete the whole set of characters by either pressing backspace deleting each character until none are left or highlighting the whole set of characters with a mouse and presses the delete key, the label appears but is in a light grey colour.
Any help you can offer with the JS would be great!
Thanks
-JaXL
Here is my solution. I added the following to the input tag and label
<label class="label-inside" for="input1" id="input1_label" title="Enter input 1">Input 1</label>
<ul class="form-input">
<li>
<input type="text" id="input1" name="myInput1" value="" autocomplete="off" title="Enter Input 1" onblur="handleBlur(this, document.getElementById('input1_label'))"
onkeydown="handleFirstClick(event, this, document.getElementById('input1_label'))"
onkeyup="handleKey(this, document.getElementById('input1_label'))" />
</li>
</ul>
And here is my Javascript
<script>
function handleBlur(input, label )
{
if ( !input.value || input.value.length == 0)
{
label.style.display = 'block';
label.style.color = 'black';
label.clickedBefore = false;
}
}
function handleFirstClick(e, input, label )
{
if ( !label.clickedBefore )
{
label.clickedBefore = true;
e.preventDefault();
label.style.color = 'red';
}
}
function handleKey(input, label)
{
console.log("handling key up : " + input.value.length);
label.style.display = 'none';
if (!input.value || input.value.length == 0 )
{
label.style.display = 'block';
label.style.color = 'red';
}
}
</script>
Let me know if something else is needed.
EDIT : adding code to add all handlers at once according to input_id.
window.onload = function(){
console.log("windows loaded");
var labels = {}
var all_labels = document.getElementsByTagName("label");
for ( var i = 0; i < all_labels.length; i++)
{
labels[all_labels[i].getAttribute("for")] = all_labels[i];
}
function attachHandlers( input_id )
{
var input = document.getElementById(input_id);
var label = labels[input_id];
input.onclick = function(e){handleFirstClick(e, input, label)};
input.onkeyup = function(e){handleKey(input, label)};
input.onblur = function(e){handleBlur(input, label)};
}
var attachInput = ["input1"];
for ( var j =0; j <attachInput.length; j++)
{
attachHandlers(attachInput[j]);
}
}
I have a default page which loads different controls on pageload according to the querystring.
I have a control which creates checkbox list (inside div_A) on load and get checkbox checked through database, then i click Continue, div_A get invisible with all the checked checkbox id in hidden field and div_B is visible true.
On Go Back click, div_B is visible false and div_A get visible true and following javascript is fired to check the selected checkbox, but it does not work
Javascript :
function goBack()
{
var SIds = document.getElementById("<%=hdv_Data.ClientID %>").value; // hdv_Data is the hidden field
var Ids_Arr = new Array();
Ids_Arr = SIds.split(',');
for (j = 0; j < Ids_Arr.length; j++)
{
if(Ids_Arr[j] != 0)
{
alert(Ids_Arr[j]); // works till here, gets correct values in array
var chk = document.getElementById(Ids_Arr[j]);
alert(chk);
chk.checked = true;
}
}
}
I wish it may help you im using this to hide and show some fields in a jsp, you may arrange it to fit your need.
- javascript
function showArea(){
var checkbox = document.getElementById('codcheckbox');
if(checkbox.value==true){
var element = document.getElementById( 'dataFields' );
if (element && element.style.display=='none'){
element.style.display='block';
}else{
element.style.display='none';
}
}
};
jsp form content...
<tbody id="dataFields" style="display: none">
<OTHER STUFF>
</tbody>