How do I auto click an options drop down? - javascript

Here is the code that I have. It does select the option, but it does not click on it. I need it to click on the option or it will not work with the rest of my script. Any way of actually simulating a click?
//Country
function setOption(selectElement, value) {
var options = selectElement.options;
for (var i = 0, optionsLength = options.length; i < optionsLength; i++) {
if (options[i].value == value) {
selectElement.selectedIndex = i;
return true;
}
}
return false;
}
setOption(document.getElementById('billCountry'), Co);
//State
function setOption(selectElement, value) {
var options = selectElement.options;
for (var i = 0, optionsLength = options.length; i < optionsLength; i++) {
if (options[i].value == value) {
selectElement.selectedIndex = i;
return true;
}
}
return false;
}
setOption(document.getElementById('billState'), Sa);
Thank you for the help.

Sounds like the problem is in the rest of your script and you may want to consider changing it to not rely on a click. Consider using a "change" event. If you really need to fire a click event something like this should do it:
var element = document.getElementById('foo');
var e = document.createEvent('MouseEvents');
e.initEvent('click', true, true);
element.dispatchEvent(e);

Related

JavaScript I have to click twice to select to element

Please anyone can help to fix the issue with my code, sometimes I have to click twice to select the next elements
var varientbtn = document.getElementsByClassName('clickthisbtn');
for(let i = 0; i < varientbtn.length; i++) {
varientbtn[i].onclick = function () {
const rbs = document.querySelectorAll('input[name="choice"]');
let selectedValue;
let varientSelectedPrice;
for (const rb of rbs) {
if (rb.checked) {
selectedValue = rb.value;
varientSelectedPrice = rb.getAttribute("data-price");
break;
}
}
document.getElementById('log').innerHTML = selectedValue;
document.getElementById('varientprice').innerHTML = varientSelectedPrice;
console.log(selectedValue, varientSelectedPrice);
}
}
Live preview:
https://codepen.io/Elkazi/pen/wvJeErg
That's because when one of labels be clicked, the checked value of related radio still not change.
Try this
const rbs = document.querySelectorAll('input[name="choice"]');
for(let i = 0; i < rbs.length; i++) {
rbs[i].addEventListener('change', function () {
let selectedValue;
let varientSelectedPrice;
for (const rb of rbs) {
if (rb.checked) {
selectedValue = rb.value;
varientSelectedPrice = rb.getAttribute("data-price");
break;
}
}
document.getElementById('log').innerHTML = selectedValue;
document.getElementById('varientprice').innerHTML = varientSelectedPrice;
console.log(selectedValue, varientSelectedPrice);
});
}
rbs[0].dispatchEvent(new Event('change'));
Since you are adding event listener to the label element, you should make use of its for attribute to get the related input field. That way you don't have to run a loop for all inputs and will always get the latest/correct value.
this will point to the element on which the event handler is called.
var varientbtn = document.getElementsByClassName('clickthisbtn');
for(let i = 0; i < varientbtn.length; i++) {
varientbtn[i].onclick = function () {
let relatedInput = document.getElementById(this.getAttribute("for"));
let selectedValue = relatedInput.value;
let varientSelectedPrice = relatedInput.getAttribute("data-price");;
document.getElementById('log').innerHTML = selectedValue;
document.getElementById('varientprice').innerHTML = varientSelectedPrice;
console.log(selectedValue, varientSelectedPrice);
}
}

Adding onClick function to select elements

I have a select tag of dynamically added elements. I need to add an event listener to each of the elements in the select tag except the first which:
adds the text of the element to a list,
makes the focus of the list the first element again, and
removes or hides the clicked element.
The first element is a 'none' element which doesn't need any event listener.
I've tried something like
for (var i = 0; i < array.length; i++)
{
var name = array[i];
var selectElement = document.getElementById(selectElementId);
addToSelectNode(document.getElementById(selectElementId), name);
var thisNode = selectElement.childNodes[i];
if (thisNode.value != "none")
{
thisNode.addEventListener("click", function(event)
{
appendNodeToList("artist-list", i);
selectElement.selectedIndex = 0;
selectElement.remove(selectElement.i);
selectElement.style.display = "none";
});
}
}
function addToSelectNode(element, optionText)
{
var newSelectElement = document.createElement("option");
newSelectElement.text = optionText;
element.add(newSelectElement);
}
function appendNodeToList(listId, text)
{
var newNode = document.createElement("LI");
var textNode = document.createTextNode(text);
newNode.appendChild(textNode);
document.getElementById(listId).appendChild(newNode);
}
Didn't work at all though
A few hours later I've solved my own question. The problem stemmed from trying to remove items in the select tag which just wasn't working - I'm nut sure if it's possible but making it disabled solved it. Anyway here's the result.
HTML:
<select id="artist-select-list">
<option value="none">none</option>
</select>
JavaScript:
window.onload = function()
{
var dropdown = document.getElementById("sampleDropdown");
var n = array.length;
// Loop to add to <select> dropdown
for (var i = 1; i <= n; i++)
{
addToSelectNode(dropdown, array[i - 1]);
}
// Loop to add id's to each element in the dropdown
for (var i = 0; i <= n; i++)
{
dropdown[i].id = "selectNum" + i;
}
// Loop to add event listener
for (var i = 0; i < dropdown.length; i++)
{
dropdown[i].addEventListener("click", function(event)
{
// Regardless of which option the user clicks move shown option to "none" (first index in dropdown)
dropdown.selectedIndex = 0;
if (event.target.id != "selectNum0")
{
// Disable once clicked
event.target.disabled = true;
// Do other things here in relation to event.target
}
});
}
}
var array =
[
"sampleText1", "sampleText2"
];
function addToSelectNode(element, optionText)
{
var newSelectElement = document.createElement("option");
newSelectElement.text = optionText;
element.add(newSelectElement);
}

Is there possible to add a moreLink to display all events in a popup regardless the space available in the dayCell?

I am trying to add a moreLink in full calendar on each day i have events and in the more link i want to force displaying all the events on that day!
this is the solutin i choose because the title of the events are very long and do not fit in a tablet or phone screen!
so far i am unsuccesfull on the days i have one single event because the function computeRowLevelLimit returns false!
i am open to any crazy idea that helps me but keep in mind that i am a java dev with minimal kowledge of js and add some extra info if possible
since i was under presure i took the matter in my own hands so here is the resolve
here i added the last else in order to be able to execute 2 methods when levelLimit is false
limitRows: function (levelLimit) {
var rowStructs = this.eventRenderer.rowStructs || [];
var row; // row #
var rowLevelLimit;
for (row = 0; row < rowStructs.length; row++) {
this.unlimitRow(row);
if (!levelLimit) {
rowLevelLimit = false;
}
else if (typeof levelLimit === 'number') {
rowLevelLimit = levelLimit;
}
else {
rowLevelLimit = this.computeRowLevelLimit(row);
}
if (rowLevelLimit !== false) {
this.limitRow(row, rowLevelLimit);
} else {
this.unlimitRow2(row);
this.addMoreLink(row);
}
}
},
The added metod are:
- one for clearing the existing links
- second for adding new links - remember this is for days with only one event
the methods are the following:
unlimitRow2: function (row) {
var rowStruct = this.eventRenderer.rowStructs[row];
var cellMatrix;
var oneDayCell;
cellMatrix = rowStruct.cellMatrix;
var _this = this;
for (i = 0; i < cellMatrix.length; i++) {
// console.log("celmatrix ", cellMatrix[i]);
oneDayCell = cellMatrix[i];
console.log("outati", oneDayCell)
if (oneDayCell.moreEls) {
oneDayCell.moreEls.remove();
oneDayCell.moreEls = null;
}
if (oneDayCell.limitedEls) {
oneDayCell.limitedEls.removeClass('fc-limited');
oneDayCell.limitedEls = null;
}
}
},
and,
addMoreLink: function (row) {
// console.log("inside addMoreMethod", row);
var rowStruct = this.eventRenderer.rowStructs[row];
var cellMatrix;
var oneDayCell;
var coloana;
var nrCol;
var td, moreWrap, moreLink;
var moreNodes = [];
var segsBelow;
// console.log ("structura randului", rowStruct);
cellMatrix = rowStruct.cellMatrix;
var _this = this;
for (i = 0; i < cellMatrix.length; i++) {
// console.log("celmatrix ", cellMatrix[i]);
oneDayCell = cellMatrix[i];
for (j = 0; j < oneDayCell.length; j++) {
coloana = oneDayCell[j];
nrCol = j;
segsBelow = _this.getCellSegs(row, nrCol);
console.log($(coloana));
moreLink = _this.renderMoreLink(row, nrCol, segsBelow);
moreWrap = $('<div/>').append(moreLink);
coloana.append(moreWrap);
moreNodes.push(moreWrap[0]);
// rowStruct.limitedEls = $(limitedNodes);
}
rowStruct.moreEls = $(moreNodes); // for easy undoing later
}
},
and for the rest i manipulated a litle bit limitRow: function (row, levelLimit)
also i had to hide the text and i choose a nasty method, not proud of it but ...
in getMoreLinkText(num) i added a last else if
else if (num === 0 ){
return '';
}

How to stop event when user clicks inside certain divs using JavaScript

I want this code to check if the user has clicked inside the open box and if so then it will keep it open, also if the user clicks outside the box it will close.
http://jsfiddle.net/MTJa5/26/
var boxes = function(){
var divClicks = document.getElementsByClassName("clickToShow");
for(i=0; i < divClicks.length; i++){
var click = divClicks[i];
var clickEvent = function(){
click.addEventListener("click", function(e){
var currentClass= this.getElementsByTagName('div')[0].className;
var divs = document.getElementsByClassName('openedBox');
for(var i = 0; i < divs.length; i++){
divs[i].setAttribute("class", "closedBox");
}
if(currentClass === "openedBox"){
this.childNodes[3].setAttribute("class", "closedBox");
} else {
this.childNodes[3].setAttribute("class", "openedBox");
}
},false);
}();
}
}();
Instead of binding several event listeners, you can also bind just one click event, and use the event.target property to check where you've clicked.
The updated code is less comples, and easier to maintain.
Demo: http://jsfiddle.net/MTJa5/28/
var hellos = function() {
function closeAllButThisBox(targ) {
var allBoxes = document.getElementsByClassName('openedBox');
for (var i=allBoxes.length-1; i>=0; i--) {
if (allBoxes[i] !== targ) {
allBoxes[i].className = 'closedBox';
}
}
}
window.addEventListener('click', function(ev) {
var targ = ev.target;
// Traverse the tree, until you hit the desired / root element
while (targ && targ !== document.documentElement) {
if (targ.className.indexOf('openedBox') !== -1) {
closeAllButThisBox(targ);
// Do nothing when clicking inside an opened box
return;
}
// This will open boxes, if closed, when clicking at the <p>
if (targ.tagName.toLowerCase() === 'p' && targ.parentNode.className.indexOf('clickToShow') !== -1) {
closeAllButThisBox(targ.parentNode);
targ.parentNode.getElementsByTagName('div')[0].className = 'openedBox';
return;
}
targ = targ.parentNode;
}
// At this point, the click is not at the right place.
// Close all boxes by removing the closedBox class names
var boxes = document.getElementsByClassName('openedBox');
for (var i=boxes.length-1; i>=0; i--) {
boxes[i].className = 'closedBox';
}
}, false);
}();

Making a row editable based on a checkbox in HTML

I have a table in HTML. The contents of this table are dynamically populated. Every row of the table has text boxes and one checkbox. When the page is loaded, all the text boxes in the rows will be in a read-only state.
Now, i want to change the state of the text boxes in a particular row to editable, if the check-box in that row is selected. Also, the text boxes should be made read-only if the check box is de-selected.
How could I accomplish this using Javascript? Please help me.
stating this with plain javascript would be pure pain :)
i suggest using jQuery, eg:
$(':checkbox').click(function() {
var checkbox = $(this);
var row = checkbox.closest('tr');
var inputText = $('input[type=text]', row);
if (checkbox.is(':checked')) {
inputText.attr('readonly', 'readonly');
}
else {
inputText.removeAttr('readonly');
}
});
otherwise
function HandleClickOnCheckbox() {
var checkbox = this;
var row;
var iter = checkbox;
while (!row) {
iter = iter.parent;
if (iter == window) {
break;
}
if (iter.tagName == 'tr') {
row = iter;
break;
}
}
if (!row) {
alert('row not found');
return false;
}
var textBoxes = GetTextBoxes(row);
var method;
if (checkbox.checked) {
var disabledAttribute = document.createAttribute('disabled');
disabledAttribute.nodeValue = 'disabled';
method = function(textBox) {
textBox.setAttributeNode(disabledAttribute);
};
}
else {
method = function(textBox) {
textBox.removeAttribute('disabled', 0);
}
}
for (var i = 0; i < textBoxes.length; i++) {
var textBox = textBoxes[i];
method(textBox);
}
}
function GetTextBoxes(element) {
var textBoxes = new Array();
for (var i = 0; i < element.children.lenght; i++) {
var child = element.children[i];
if (child.tagName == 'input') {
if (child.type == 'text') {
textBoxes.push(child);
}
}
if (child.tagName == 'td') {
var childTextBoxes = GetTextBoxes(child);
if (childTextBoxes.length) {
for (var j = 0; j < childTextBoxes.length; j++) {
var childTextBox = childTextBoxes[j];
textBoxes.push(childTextBox);
}
}
}
}
return textBoxes;
}
this is not tested!
Perhaps, you can start by handling the click event of the checkbox using an if/else statement to check if the checkbox is actually checked. If it is you can use the row within which the checkbox resides to find all the textboxes in the different cells and enable/disable them.
Are you using JQuery or plain Javascript?
If you don't mind using jQuery, you could do:
$('checkbox').click(function() {
if ($(this).attr('checked')) {
$(this).parents('tr').children('input[type="text"]').each().attr('readonly', 'readonly');
} else {
$(this).parents('tr').children('input[type="text"]').each().removeAttr('readonly');
}
})
Or something like that. I'd have to test it to be sure.
Edited to reflect Andreas's comment.
Try this snippet (assumes that the checkbox has a class called "checkbox") if you are using Jquery.
jQuery('tr.checkbox').click(function() {
if (jQuery(this).is(":checked")) {
jQuery('td', this).removeAttr('disabled');
} else {
jQuery('td', this).attr('disabled', '');
}
});`

Categories

Resources