I want to fill my Selection by Script. I am struggling with the filling method.
When I want to fill my FontSizeMenu I use this code:
function FillFontSizeMenu() { // run this at Start
FillSelection(GetPossibleFontSizes(), "fontSizeMenu"); // Fill the selection with values
}
function GetPossibleFontSizes(){ // Return all values for the menu
var sizeMin = 1;
var sizeMax = 100;
var possibleSizes = [];
for(var i = sizeMin; i <= sizeMax; i++)
{
possibleSizes.push(i);
}
return possibleSizes;
}
function FillSelection(possibleValues, elementId){ // Fill the menu
for(var i = 0; i < possibleValues.length; i++)
{
var optionElement = "<option></option>"; // add one option element per value
optionElement.html(possibleValues[i]);
optionElement.val(possibleValues[i]);
$(elementId).append(optionElement); // add the option element to the selection
}
}
Something is wrong with the "FillSelection" method, it says the option element is not a function.
Does someone knows what is wrong or missing?
Thanks
Wrap html string in jQuery()
var optionElement = $("<option></option>");
You can also use jQuery() to set html, value and call .appendTo()
$("<option></option>", {
html: possibleValues[i],
value: possibleValues[i],
appendTo: $(elementId)
});
Here is one more solution
You need to create new Option object
$(elementId).append(new Option("Font size "+i, possibleValues[i]));
and you should pass #id to function:
FillSelection(GetPossibleFontSizes(), "#fontSizeMenu")
function FillFontSizeMenu() { // run this at Start
FillSelection(GetPossibleFontSizes(), "#fontSizeMenu"); // Fill the selection with values
}
function GetPossibleFontSizes(){ // Return all values for the menu
var sizeMin = 1;
var sizeMax = 100;
var possibleSizes = [];
for(var i = sizeMin; i <= sizeMax; i++)
{
possibleSizes.push(i);
}
return possibleSizes;
}
function FillSelection(possibleValues, elementId){ // Fill the menu
for(var i = 0; i < possibleValues.length; i++)
{
$(elementId).append(new Option("Font size "+i, possibleValues[i])); // add the option element to the selection
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="FillFontSizeMenu()">Populate it</button>
<select id="fontSizeMenu">
</select>
You have to create an element first then append properties using jquery. Something like this
var ele = document.createElement("<option>");
$("body").append(ele);
$(ele).html(possibleValues[i]);
$(ele).val(possibleValues[i]);
Related
What I'm trying to do is make it open the breed_selector dropdown menu, and then select breed1, then .click, then move onto the next breed and click, and continue, It needs to do this three times, but unfortunately it only selects the first breed of dog and clicks, not all three.
Thanks
(function() {
var x = document.getElementById("breed_selector).options;
for(var i=0;i<x.length;i++){
if(x[i].text=="Labrador"){
x[i].selected=true;
document.getElementsByClassName("shop")[0].click();
break;
}
}
var x = document.getElementById("breed_selector").options;
for(var i=0;i<x.length;i++){
if(x[i].text=="poodle"){
x[i].selected=true;
document.getElementsByClassName("shop")[0].click();
})();
At the moment, it just doesn't do anything,
I have tried
var = document.getElementById("breed_selector").options;
for(var i=0;i<x.length;i++){
if(x[i].text=="poodle", "Labrador", "pug"){
x[i].selected=true;
document.getElementsByClassName("shop")[0].click();
break;
But the above doesn't work either, any input would be great, Thanks :)
UPDATED CODE which still doesn't work
(function() {
var x = document.getElementById("breed_selector").options;
for(var i=0;i<x.length;i++){
var text = x[i].text;
if(x[i].text === "Labrador" && text === "Pug"){
x[i].selected=true;
document.getElementsByClassName("shop")[0].click();
break;
}
}
})();
You could try this to click on ALL the options of the select element:
var breedSelector = document.getElementById("breed_selector");
var howMany = breedSelector.length;
var buttonShop = document.querySelector(".shop");
for (var i = 0; i < howMany; i++) {
breedSelector.selectedIndex = i;
buttonShop.click();
}
Note, though, that it will click the button several times in quick succession.
In order to select only certain options based on their value, you could try something like:
var breedSelector = document.getElementById("breed_selector");
var whichOnes = ["Labrador", "Poodle", "Golden"]; //whichever you want.
var buttonShop = document.querySelector(".shop");
whichOnes.forEach(function(breed){
breedSelector.selectedIndex = [].findIndex.call(breedSelector, function(option) { return option.textContent == breed});
buttonShop.click();
}
I have a slider input field that gives a numeric value when slid. I would like to clone an object X times based on the slider value, however when I try to accomplish this it creates an endless loop. Is there anyway to get the number of cloned elements to match the slider value when it changes? Here is the code I was using.
jQuery(document).ready(function($) {
$(window).load(function() {
$('input#fieldname3_1').change(function() {
var e = $('#student-icons.icon > span');
var n = $('#fieldname9_1').val();
$('#student-icons.icon').html(
for (var i = 0; i < n; i++) {
e.clone().insertAfter(e);
});
}).change()
});
});
Try the following setup:
HTML:
<input type="range" id='fieldname3_1' style='width: 200px'>
<div id='student-icons' class='icon'></div>
JavaScript:
$(document).ready(function($) {
$('input#fieldname3_1').change(function() {
var n = $(this).val();
// reset the element
$('#student-icons.icon').html('');
for (var i = 0; i < n; i++) {
// The html of what you want to clone goes here
$('#student-icons.icon').append("<div id='hello'>"+i+"</div>")
}
});
});
I also recommend using the oninput event if browser support is not an issue (IE 9 and up only):
$(document).ready(function($) {
$('input#fieldname3_1')[0].oninput = function() {
var n = $(this).val();
$('#student-icons.icon').html('');
for (var i = 0; i < n; i++) {
$('#student-icons.icon').append("<div id='hello'>"+i+"</div>")
}
};
});
This will allow the event to fire as soon as the input is changed rather than wait on the keydown.
JsFiddle
JsFiddle w/ onInput
I am working on a form, and I would like to reset the lines individually without using reset.
How to vary the values of the attribute passed as parameter of the method getElementById in JavaScript using a loop?
Here is an example of my source code below:
<script>
var element = document.getElementById('#re');
element.addEventListener('click', function() {
document.getElementById("#id1").value = "";
document.getElementById("#id2").value = "";
document.getElementById("#id3").value = "";
});
</script>
Assuming your IDs have the format shown in your example:
for (var i = 1; i <= 3; i++) {
document.getElementById("id" + i).value = "";
}
If that's not the case but you know the ID of every element you can put all IDs in an array and use that:
var elementIds = ["id1", "id2", "id3"];
elementIds.forEach(function(id) {
document.getElementById(id).value = "";
});
Another solution is to give all the elements you want to reset a specific class and target that:
var elements = document.getElementsByClassName("resetable-element");
[].slice.call(elements).forEach(function(element) {
element.value = "";
});
Instead of using ids, you can loop through your inputs for example:
var inputs = document.querySelectorAll("input");
for (var i = 0; i < inputs.length; i++) {
inputs[i].value = "";
}
For your simple example, you could loop through the values 1 - 3 (I assume the # in the ID is a typo?):
for(var i = 1; i <= 3; i++) {
document.getElementById('id' + i).value = '';
}
If you can identify the elements by something else, such as a class name, you might prefer to iterate over that:
var elements = document.querySelectorAll('.field');
Array.prototype.slice.call(elements).forEach(function(element) {
element.value = '';
});
i am new to js.
i am trying to grab a image from an array with similar class names which
has a specific src saved in a variable bigImgPath
here is my Updated Code..
var moniqueThumbs=document.getElementsByClassName('moniqueThumbs'); // Grab the ThumbNails
var bigImagesList=document.getElementsByClassName('monique-image'); // Grabs All Big Images
var currentBigImg='';
var currentBigImageFilePath=""; // Current Big Image path Captured by current Thumb Click //s
for(var i = 0; i < moniqueThumbs.length; i++){
moniqueThumbs[i].addEventListener("click", grabBigImgPath); // Added a myFunction Click event to Thumbs
}
// Grab Big Image Path from Clicked Thumb
function grabBigImgPath()
{
currentBigImageFilePath=this.getAttribute('data-bigImgPath'); // grabs the current bigPath from the thumb//
var currentBigImageToDisplay;
for (var i = 0; i < bigImagesList.length; i++)
{
if (bigImagesList[i].getAttribute('src') == currentBigImageFilePath)
{
currentBigImageToDisplay = bigImagesList[i];
console.log(currentBigImageToDisplay);
break;
}
}
}
Still not displaying the current image in console.log
You need to use the getAttribute method to get the src:
currentBigImageToDisplay = bigImagesList[i].getAttribute('src') == bigImgPath;
That's still not right however, as it will just return true or false, so you want something like:
var currentBigImageToDisplay;
for (var i = 0; i < bigImagesList.length; i++) {
if (bigImagesList[i].getAttribute('src') == bigImgPath) {
currentBigImageToDisplay = bigImagesList[i];
break;
}
}
Alternatively, you could use the filter syntax:
bigImagesList = Array.prototype.slice.call(bigImagesList);
var currentBigImageToDisplay = bigImagesList.filter(function(item) {
return item.getAttribute('src') == bigImgPath;
})[0]
Working JSFIddle
I am trying to use <label> elements in my html contact form like the HTML5 placeholder attribute for inputs. I have written the following JavaScript to to act as a reusable function witch will provide the following functionality.
Find the input by name.
Get the value of the input.
Find the label belonging to the input.
Change the label style depending on the state of the input.
Change the label style depending on the value of the input.
However it is not working and I don't know why as no errors appear in the console. What am I doing wrong? here is a JS Fiddle with code
function placeholder(field_name) {
// Get the input box with field_name
// Then get input value
var box = document.getElementsByName(field_name);
var i;
for (i = 0; i < box.length; i++) {
var value = document.getElementById(box[i].value);
}
// Get the labels belonging to each box using the HTML for attribute
var labels = document.getElementsByTagName('LABEL');
for (i = 0; i < labels.length; i++) {
if (labels[i].htmlFor !== '') {
var elem = document.getElementById(labels[i].htmlFor);
if (elem) {
box.label = labels[i];
}
}
}
// Colors
var focusColor = "#D5D5D5";
var blurColor = "#B3B3B3";
// If no text is in the box then show the label grey color
box.onblur = function () {
box.label.style.color = blurColor;
};
// If input focuses change label color to light grey
box.onfocus = function () {
box.label.style.color = focusColor;
};
// If there is text in the box then hide the label
if (box.value !== "") {
// Quick do something, hide!
box.label.style.color = "transparent";
}
}
// Call the function passing field names as parameters
placeholder(document.getElementsByName("email"));
placeholder(document.getElementsByName("firstName"));
placeholder(document.getElementsByName("lastName"));
This might be considered a little overkill on the number of listeners I've used, feel free to remove any you think unnecessary, but I've tried to employ your HTML structure as you have it and give you all desired effects. It should work for either the <label>s for matching the <input>s id OR matching it's <name> (given no id matches). I'll always say prefer using an id over name. I believe this JavaScript should also work in all browsers too, except the addEventListener for which you'd need a shim for old IE versions (let me know if it doesn't in one/the error message).
Demo
var focusColor = "#D5D5D5", blurColor = "#B3B3B3";
function placeholder(fieldName) {
var named = document.getElementsByName(fieldName), i;
for (i = 0; i < named.length; ++i) { // loop over all elements with this name
(function (n) { // catch in scope
var labels = [], tmp, j, fn, focus, blur;
if ('labels' in n && n.labels.length > 0) labels = n.labels; // if labels provided by browser use it
else { // get labels from form, filter to ones we want
tmp = n.form.getElementsByTagName('label');
for (j = 0;j < tmp.length; ++j) {
if (tmp[j].htmlFor === fieldName) {
labels.push(tmp[j]);
}
}
}
for (j = 0; j < labels.length; ++j) { // loop over each label
(function (label) { // catch label in scope
fn = function () {
if (this.value === '') {
label.style.visibility = 'visible';
} else {
label.style.visibility = 'hidden';
}
};
focus = function () {
label.style.color = focusColor;
};
blur = function () {
label.style.color = blurColor;
};
}(labels[j]));
n.addEventListener('click', fn); // add to relevant listeners
n.addEventListener('keydown', fn);
n.addEventListener('keypress', fn);
n.addEventListener('keyup', fn);
n.addEventListener('focus', fn);
n.addEventListener('focus', focus);
n.addEventListener('blur', fn);
n.addEventListener('blur', blur);
}
}(named[i]));
}
};
placeholder("email"); // just pass the name attribute
placeholder("firstName");
placeholder("lastName");
http://jsfiddle.net/cCxjk/5/
var inputs = document.getElementsByTagName('input');
var old_ele = '';
var old_label ='';
function hide_label(ele){
var id_of_input = ele.target.id;
var label = document.getElementById(id_of_input + '-placeholder');
if(ele.target == document.activeElement){
label.style.display = 'none';
}
if (old_ele.value == '' && old_ele != document.activeElement){
old_label.style.display = 'inline';
}
old_ele = ele.target;
old_label = label;
}
for(var i = 0; i < inputs.length; i++){
inputs[i].addEventListener('click', hide_label);
}
I will point out a couple things, you will have to find away around the fact that the label is inside the input so users now can't click on half of the input and actually have the input gain focus.
Also I guess you want to do this in IE (otherwise I would strongly advise using the html5 placeholder!) which means you would need to change the ele.target to ele.srcElement.