I'm trying to use a chrome extension (shortkeys) to create shortcut keys that can press buttons within our warehouse management system (so they can be matched to barcodes).
One of the buttons has no ID, and once it has been clicked the button innertext changes. Ideally I'd like the shortcut to work on either version of the button
It is either
<input type="submit" value="Create Shipment" class="btn btn-success pull-right">
or
<a class="btn btn-success" href="/Order/OrderDocumentP/15467" target="_blank">Print Label</a>
I then have another button to be assigned to a different shortcut key
<a class="btn btn-success" href="/Picking/DespatchOrder?OrderId=13413">Despatch</a>
But I'm sure once I've figured out the first one the next will be easier :)
Any help greatly appreciated, I've been through a number of other questions that are similar but not quite what I'm after and my JS knowledge is pretty rubbish
Learn CSS a bit and use https://developer.mozilla.org/ru/docs/Web/API/Document/querySelector
Your extensions probaply supports that
// cuz I don't like to type long "document.querySelector"
q = sel => document.querySelector(sel)
qq = sel => document.querySelectorAll(sel)
function clickOnly(sel) {
let list = qq(sel);
if (list.length == 1) list[0].click();
else alert('element "'+sel+'" is not unique!');
}
// handles *any* keypress
onkeypress = function (event) {
if (event.target.tagName == "INPUT") return; // noop on input focused
if (event.target.tagName == "TEXTAREA") return; // noop on input focused
console.log(event.code); // to see what the key is
let rawCode = event.code; // keyboard key, `KeyM` for M, `Digit7` for 7, `Slash` for /
let code = rawCode; // make CtrlAltShiftKeyM
if (event.shiftKey) code = 'Shift' + code;
if (event.altKey) code = 'Alt' + code;
if (event.ctrlKey) code = 'Ctrl' + code;
if (!kds[event.code]) return;
event.preventDefault(); // prevent CtrlKeyM browser handler for bookmarks or whatever
kds[event.code](event);
}
kds = {}
// it's a function so starts with `() => `
kds.KeyM = () => alert('it works!')
// a is for <a>, [href^=] is for href starts with
kds.ShiftKeyM = () => clickOnly('a[href^="/Order/OrderDocumentP/]')
// , is for one of multiple selectors
kds.CtrlKeyM = () => clickOnly('input[value="Create Shipment"], a[href^="/Order/OrderDocumentP/]')
This is a simple script on getting a button by class name and clicking it. I think this is what you are looking for, if not let me know I will rewrite it.
EDIT: I added a loop that will click all buttons or links found with the class name btn-success
I've inserted a second function so people looking for a solution by classname can also still find the first one. AutoClickBtnByValue() will click the button with inner text "click me now".
function AutoClickBtn() {
var button = document.getElementsByClassName("btn-success");
for (var i = 0; i < button.length; i++) {
button[i].click();
console.log('Success! Clicked button' + i);
}
}
setInterval(AutoClickBtn, 2000);
/* Click button by innerHTML text */
function AutoClickBtnByValue() {
var button = document.getElementsByClassName("btn-success");
for (var i = 0; i < button.length; i++) {
if (button[i].innerHTML.indexOf('click me now') > -1) {
button[i].click();
console.log('Success! Clicked button' + i + ' with value: "click me now" ');
}
}
}
setInterval(AutoClickBtnByValue, 2000);
<input type="submit" value="Create Shipment" class="btn btn-success pull-right">
<a class="btn btn-success" href="#" target="_blank">Print Label</a>
<a class="btn btn-success" href="#">Despatch</a>
<button class="btn-success">click me now</button>
Related
I am trying to do a web app similar to google calendar. I have done the object and methods within it but now it's time to be able to add what I want as a task. My idea is for the user to add something to the input and that input being console.logged for now.
Any idea?
HTML
<div class="new-task" id="task-input">
<div id="add-new-task">Task: <input type="text"></div>
<div id="add-time">Time: <input type="text"></div>
<button class ="save-task" onclick="">Save task</button>
</div>
Javascript
var idCounter = 0
var tasksManager = {
array: [],
add: function(task){
taskObject = {
title: task,
idVerification: idCounter ++
}
tasksManager.array.push(taskObject)
},
show:function(id){
var i;
for (i = 0; i < tasksManager.array.length; i++) {
if(id === tasksManager.array[i].idVerification){
return tasksManager.array[i]
}
}
},
delete:function(task){
if(this.show){
tasksManager.array.splice(task)
}
}
}
var newTask = document.getElementById("add-new-task")
newTask.addEventListener('click',tasksManager.add())
console.log(tasksManager.array)
As you can see with console.log above the array index [0] is logged as undefined but I wanted the user to write in the input " Go to the gym" and this to be logged within the array.
Thanks
Some issues:
You are not assigning the click handler. Instead you execute it immediately (not on click).
When you call .add() you don't provide an argument: the name of the task
The click handler should be on the button element, not on the div that has the input element. And so it will be useful to give that button an id attribute.
You should retrieve the value from the input element, and so it would be more appropriate to give that element an id and not so much the div that wraps it.
The console.log at the end of your script is executed immediately. It should be done only when the user has clicked the button.
Snippet with some corrections (also in the HTML!):
var idCounter = 0
var tasksManager = {
array: [],
add: function(task){
let taskObject = {
title: task,
idVerification: idCounter ++
}
tasksManager.array.push(taskObject)
},
show:function(id){
var i;
for (i = 0; i < tasksManager.array.length; i++) {
if(id === tasksManager.array[i].idVerification){
return tasksManager.array[i]
}
}
},
delete:function(task){
if(this.show){
tasksManager.array.splice(task)
}
}
}
var button = document.getElementById("save-task"); // <-- the button
var input = document.getElementById("add-new-task"); // <-- the input (move the ID attribute to the input!)
button.addEventListener('click', () => {
tasksManager.add(input.value);
console.log(tasksManager.array)
})
<div class="new-task" id="task-input">
<div >Task: <input id="add-new-task" type="text"></div>
<div id="add-time">Time: <input type="text"></div>
<button class ="save-task" id ="save-task" onclick="">Save task</button>
</div>
hi guys i need some help with javascript,
i have a toggle function for my text, waht you can see on www.jasperscheper.nl
but i want to make the text stay when you double click on over mij and home.
this is my code:
var bannerText1 = document.getElementById('bannertext1');
var bannerText2 = document.getElementById('bannertext2');
var displayedBannerText = 1;
function toggleBannerText() {
if(displayedBannerText == 1) {
// Switch to bannertext 2
bannerText1.className += ' hidebannertext';
displayedBannerText = 2;
bannertext2.className = 'welkom';
} else {
bannertext2.className += ' hidebannertext';
displayedBannerText = 1;
bannerText1.className = 'welkom';
}
}
<li class="knop" >
<button class="button" href="#"onclick="toggleBannerText()"> <h3>Home</h3></button>
</li>
<li class="knop">
<button class="button" onclick="toggleBannerText()" href="#"><h3>Over mij</h3></button>
</li>
thanks in advance,
Jasper Scheper.
Problem: You are calling the function toggleBannerText() every time there is a click on any of the buttons, There is no where the button's click events are distinguished, So every click assumes you need to show other text than the one shown.
Solution: Change your HTML to pass a parameter into the function saying which section it wants to show. Eg: toggleBannerText('Home')
<li class="knop" >
<button class="button" href="#"onclick="toggleBannerText('Home')"> <h3>Home</h3></button>
</li>
<li class="knop">
<button class="button" onclick="toggleBannerText('Over')" href="#"><h3>Over mij</h3>
</button> <!-- There was a typo you had a </a> here I changed it -->
</li>
Now change your function to accept the parameter and show that particular Text .
function toggleBannerText(section) {
if(section === "Over") {
// Switch to bannertext 2
bannerText1.className = 'hidebannertext'; // I have removed the +
bannertext2.className = 'welkom';
}
else if (section === "Home"){
bannertext2.className = 'hidebannertext'; // + has been removed
bannerText1.className = 'welkom';
}
else{
// none of the two buttons were clicked.
}
}
I have tested this code against your site and its working fine
I have form which gets clone when user click on add more button .
This is how my html looks:
<div class="col-xs-12 duplicateable-content">
<div class="item-block">
<button class="btn btn-danger btn-float btn-remove">
<i class="ti-close"></i>
</button>
<input type="file" id="drop" class="dropify" data-default-file="https://cdn.example.com/front2/assets/img/logo-default.png" name="sch_logo">
</div>
<button class="btn btn-primary btn-duplicator">Add experience</button>
...
</div>
This my jquery part :
$(function(){
$(".btn-duplicator").on("click", function(a) {
a.preventDefault();
var b = $(this).parent().siblings(".duplicateable-content"),
c = $("<div>").append(b.clone(true, true)).html();
$(c).insertBefore(b);
var d = b.prev(".duplicateable-content");
d.fadeIn(600).removeClass("duplicateable-content")
})
});
Now I want every time user clicks on add more button the id and class of the input type file should be changed into an unique, some may be thinking why I'm doing this, it I because dropify plugin doesn't work after being cloned, but when I gave it unique id and class it started working, here is what I've tried :
function randomString(len, an){
an = an&&an.toLowerCase();
var str="", i=0, min=an=="a"?10:0, max=an=="n"?10:62;
for(;i++<len;){
var r = Math.random()*(max-min)+min <<0;
str += String.fromCharCode(r+=r>9?r<36?55:61:48);
}
return str;
} var ptr = randomString(10, "a");
var className = $('#drop').attr('class');
var cd = $("#drop").removeClass(className).addClass(ptr);
Now after this here is how I initiate the plugin $('.' + ptr).dropify().
But because id is still same I'm not able to produce clone more than one.
How can I change the id and class everytime user click on it? is there a better way?
Working Fiddle.
Problem :
You're cloning a div that contain already initialized dropify input and that what create the conflict when you're trying to clone it and reinitilize it after clone for the second time.
Solution: Create a model div for the dropify div you want to clone without adding dropify class to prevent $('.dropify').dropify() from initialize the input then add class dropify during the clone.
Model div code :
<div class='hidden'>
<div class="col-xs-12 duplicateable-content model">
<div class="item-block">
<button class="btn btn-danger btn-float btn-remove">
X
</button>
<input type="file" data-default-file="http://www.misterbilingue.com/assets/uploads/fileserver/Company%20Register/game_logo_default_fix.png" name="sch_logo">
</div>
<button class="btn btn-primary btn-duplicator">Add experience</button>
</div>
</div>
JS code :
$('.dropify').dropify();
$("body").on("click",".btn-duplicator", clone_model);
$("body").on("click",".btn-remove", remove);
//Functions
function clone_model() {
var b = $(this).parent(".duplicateable-content"),
c = $(".model").clone(true, true);
c.removeClass('model');
c.find('input').addClass('dropify');
$(b).before(c);
$('.dropify').dropify();
}
function remove() {
$(this).closest('.duplicateable-content').remove();
}
Hope this helps.
Try this:
$(function() {
$(document).on("click", ".btn-duplicator", function(a) {
a.preventDefault();
var b = $(this).parent(".duplicateable-content"),
c = b.clone(true, true);
c.find(".dropify").removeClass('dropify').addClass('cropify')
.attr('id', b.find('[type="file"]')[0].id + $(".btn-duplicator").index(this)) //<here
$(c).insertBefore(b);
var d = b.prev(".duplicateable-content");
d.fadeIn(600).removeClass("duplicateable-content")
})
});
Fiddle
This does what you specified with an example different from yours:
<div id="template"><span>...</span></div>
<script>
function appendrow () {
html = $('#template').html();
var $last = $('.copy').last();
var lastId;
if($last.length > 0) {
lastId = parseInt($('.copy').last().prop('id').substr(3));
} else {
lastId = -1;
}
$copy = $(html);
$copy.prop('id', 'row' + (lastId + 1));
$copy.addClass('copy');
if(lastId < 0)
$copy.insertAfter('#template');
else
$copy.insertAfter("#row" + lastId);
}
appendrow();
appendrow();
appendrow();
</script>
Try adding one class to all dropify inputs (e.g. 'dropify'). Then you can set each elements ID to a genereted value using this:
inputToAdd.attr('id', 'dropify-input-' + $('.dropify').length );
Each time you add another button, $('.dropify').length will increase by 1 so you and up having a unique ID for every button.
I have an HTML page with 2 divs (among other things) - "person" and "person-success", in which "person" is visible and "person-success" hidden. When a button in "person" is clicked, the visible div hides and the previously-hidden div "person-success" shows. The code is given below:
<div id="person">
<br><br>
<div id="counterNum" class="counter-color" l10nID="M_AC_UT_TXT_20"></div>
<div role="form">
...
<button type="submit" id="addPerson" class="btn btn-success" l10nID="M_LG_BTN_1"></button>
</div>
</div>
<div id="person-success" class="hide">
...
<p>
<span l10nID='M_AC_UT_TXT_19'></span>
You can add <span id="limit"></span> more people. <a href='<?php echo $root; ?>edituseraccount.php?action=addPerson'>Add another person?</a>
</p>
</div>
The JavaScript:
$('#addPerson').click(function() {
var counter = 0;
var limit = 10;
var args = {
...
$.post("addperson.php",args,function(data){
var response = JSON.parse(data);
if(response.status == 0){
counter += 1;
if (counter < limit){
$('#counterNum').text(counter);
$('#person').hide();
$('#limit').text(limit-counter);
$('#person-success').show();
}
}
console.log(data);
});
});
Now, when the button is pressed, while "person-success" will show, clicking on "Add another person?" should show "person" and hide "person-success" again. Only this time, the div "counterNum" should be updated with the value of "counter" from the JavaScript. With my code, clicking the link reopens the "person" div and hides the other, but counterNum is not updated, or even shown. Does anyone know how I could do that?
I hope I could explain my problem. Would be grateful for any help!!
Var counter Make it as global. Because each time when you click on the addPerson button when counter resets to zero.
var counter = 0;
var limit = 10;
$('#addPerson').click(function() {
var args = {
...
$.post("addperson.php",args,function(data){
var response = JSON.parse(data);
if(response.status == 0){
counter += 1;
if (counter < limit){
$('#counterNum').text(counter);
$('#person').hide();
$('#limit').text(limit-counter);
$('#person-success').show();
}
}
console.log(data);
});
});
The variable you declare is local scope.
Declare variable globally outside the click event called.
On each click it resets counter to 0.
Hope it helps !!!
I have a button and when I click it, I want the html object (aka button) to be passed as a parameter to another javascript function. I want the javascript function to print the data-hi from the element in the button.
HTML BUTTON
<button type = "button" onclick = "whoIsRdns(this)" class="dns-information btn btn-xs btn-info pull-right" data-toggle="modal" data-target = "#whois_rdns_modal" data-path="{{ path( '_who_is_rdns', { 'peer': peer.number, 'ip': peer.mac } ) }}" data-hi = "hi2">
<i class="icon-search"></i>
</button>
JS FUNCTION(W/ JQUERY)
function whoIsRdns(thisButton){
//Enable jQuery properties from the param of the HTML object
var btn = $(thisButton);
var test = btn.data('hi');
console.log('Value is ' + test);
}
Why would test return as null?
Shouldn't var btn = $("thisButton"); be var btn = $(thisButton); (without quotes)
Just a typo
$("thisButton") !== $(thisButton);
drop the quotes so you are not looking for an element with a tag name thisButton
var btn = $("thisButton");
needs to be
var btn = $(thisButton);