Best way to combine multiple functions for clarity? - javascript

I have a text input box which does 3 things, it begins with the button 'Report A Bug' when it is closed, upon clicking it opens a text box & the Report A Bug button becomes 'Close'. I now want to combine the code from all JS below to work with with the following HTML Button, but I can't see a clear way to move forward on this. When I've tried my functionality has disappeared, or button simply no longer changes text.
Button HTML.
<button id="myBtnToReportABug" onclick="toggleReportForm()" type="button" class="btn btn-secondary float-right">{{#if report_form_closed }} Report A Problem {{else}} Close {{/if}}</button> </div>
JS:
// changes text on 'report problem' button when form open
function change() {
var theButton = document.getElementById("myBtnToReportABug");
if (theButton.innerHTML == "Close")
theButton.innerHTML = "Report A Problem";
else
theButton.innerHTML = "Close";
}
// clears text field onclick
function clearFields() {
document.getElementById("nameInput").value = "";
}
// changes text on 'submit' back to original button text when report is made
function changeSecond() {
var theButton = document.getElementById("myBtnToReportABug");
if (theButton.innerHTML == "Close")
theButton.innerHTML = "Report A Problem";
}
function toggleReportForm() {
var report_form_closed = document.getElementById("myBtnToReportABug");
}

try using addEventListener;
eg.
function callback(){
//all the functions call them here
}
document.getElementById("myBtnToReportABug").addEventListener(callback)

Related

Button to clear input value

I am trying to make a button (id="delete") that will clear any text entered in my field (id="input"), I have made a function and button, however after pressing the button nothing happens. Can't find the issue, the console also doesn't give any errors. Will be thankful for your assistance.
HTML:
<span contenteditable="true" ><p id="input"></p></span>
<button id="delete">Delete Data</button>
JS:
const trigger = document.getElementById("delete");
trigger.value = '';
Thanks!
If you want to take action when a button is clicked, you should listen for its "click" event.
document.querySelector("#delete").addEventListener('click', () => {
document.getElementById("input").innerHTML = ''
})

Click - Add text - Active textbox

I would like to add text to the active textbox when a button is clicked.
I have read many threads explaining how it is done when one is wishing to add to a specific textbox but nothing on simply adding text to whichever text field is active...
Any help would be appreciated. Thanks.
The below is a solution for a virtual keyboard.
Pure JS + HTML:
function bind() {
var keyArr = document.getElementsByClassName('key');
for(var i = 0; i < keyArr.length; i++) {
keyArr[i].addEventListener('click', function() {
document.getElementById('textinput').value += this.innerHTML;
});
}
var capsLock = document.getElementById('capslock');
capsLock.addEventListener('click', function() {
for(var i = 0; i < keyArr.length; i++) {
if(capsLock.capsactive) {
keyArr[i].innerHTML = keyArr[i].innerHTML.toLowerCase();
} else {
keyArr[i].innerHTML = keyArr[i].innerHTML.toUpperCase();
}
}
capsLock.capsactive = !capsLock.capsactive;
});
}
<body onload='bind()'>
<input id='textinput'><br>
<button class='key'>q</button>
<button class='key'>w</button>
<button class='key'>e</button>
<button class='key'>r</button>
<button class='key'>t</button>
<button class='key'>y</button><br>
<button id='capslock' capsactive=false>CapsLock</button>
</body>
You can access a textbox's value by element.value or by $(selector).val().
For changing, use: element.value = newvalue; (JS) or $(selector).val(newvalue); (jQuery).
In the example, ...addEventListener... attaches a function to each button. The function, here, changes the value of the textinput textbox, to be the previous value + the text of the button which was pressed.
For instance, if the even the capsLock button is given the class key, on clicking capsLock, the text "Caps Lock" will be appended to the textbox.
Note: This solution covers adding text to a definite field. If there are multiple textbox-es present on the page, and the text has to be added to the currently focused one, a different approach has to be taken:
var lfl = -1, capsactive = false;
$(document).ready(function() {
$('*').blur(function() {
lfl = this;
});
$('.key').click(function() {
if($(lfl).hasClass('vkballowed')) {
$(lfl).val($(lfl).val() + $(this).html());
$(lfl).focus();
}
});
$('#capslock').click(function() {
capsactive = !capsactive;
if(capsactive == true) {
$('.key').each(function() {
$(this).html($(this).html().toUpperCase());
});
} else {
$('.key').each(function() {
$(this).html($(this).html().toLowerCase());
});
}
$(lfl).focus();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<input id='input0' class='vkballowed'><p>Editable</p><br>
<input id='input1' class='vkballowed'><p>Editable</p><br>
<input id='input2'><p>Not Editable</p><br>
<button class='key'>q</button>
<button class='key'>w</button>
<button class='key'>e</button>
<button class='key'>r</button>
<button class='key'>t</button>
<button class='key'>y</button><br>
<button id='capslock'>CapsLock</button>
Example instructions: Focus on the Editable text-fields, then press a key on the virtual-keyboard, so that corresponding text is appended to the fields. The virtual-keyboard doesn't work on the Not Editable text-field.
Here, the last element on the page that lost focus (was blurred) is stored in a variable. Next, whenever a key on the virtual-keyboard is pressed, first, it is checked whether the keyboard is allowed on that control, then the button's text is appended to the control, and finally, the control is given its focus back. Note that if the class vkballowed is added to controls such as buttons, no action would be effective on those controls. On other controls such as textareas, which have a value property, the virtual-keyboard will be functional.
The above approach isn't wholly correct. If, for instance, a key on the virtual-keyboard is pressed right after some other interactive button on the page, that button would receive focus again (this may not re-cause the action attached to that button, though). It, hopefully, gives you a starting point though.
jquery
$('#buttonId').click(function(event) {
$('.tstboxClass').val('heelo i am text box value.');
})

Popup form on hover - how to make it the only one on the page?

I have 5 buttons 'Free call' on my site. On hover on them pops up contact form. I have a number of problems with it:
How to make the form be the only one on the page? I mean, from different buttons must be shown the same form. (For ex. I filled in the form in one place and when I hover other button, I see message 'You're done' or smth like that)
How to make the showing function work only once for every button? (The code below)
I tried to solve this problems but my methods didn't work
HTML
I have 5 such buttons on the page in different places
function showForm() {
var currentButton = $(this);
if ( currentButton.find('.popover-form') !== undefined ) {
var freeCallForm = "<form class=\"popover-form free-call-form\"><label for=\"\">Name</label><input type=\"text\"> <label for=\"\">Phonenum</label><input type=\"text\" value=\"+375\"><button>Call me!</button> </form>";
currentButton.append(freeCallForm);
}
}
$('.main-btn').on('mouseover', showForm);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="main-btn free-call">
<p>Use free call
<br/>
<i class="glyphicon glyphicon-chevron-down"></i>
</div>
This function above unfortunately doesn't work. With if I tried to make function work only when .main-btn hasn't .popover-form.
And other problem is that on hover on different buttons anyway appends NEW form for every button. I can't find correct solution for this problem.
var isOpen = false;
function showForm() {
var currentButton = $(this);
if ( currentButton.find('.popover-form') !== undefined && !isOpen) {
var freeCallForm = "<form class=\"popover-form free-call-form\"><label for=\"\">Name</label><input type=\"text\"> <label for=\"\">Phonenum</label><input type=\"text\" value=\"+375\"><button>Call me!</button> </form>";
isOpen = true;
currentButton.append(freeCallForm);
}
}
$('.main-btn').on('mouseover', showForm);
//on modal close set isOpen back to false
The solution is the append() method. It moves DOM elements, not copies them (I thought so).
So I inserted my <form id="free-call-form"> to the end of the document, before </body>.
JS
function showForm() {
var currentButton = $(this);
if ( ( currentButton.find('.popover-form') !== undefined && !currentButton.existsFreeCall ) ) {
var freeCallForm = $('#free-call-form');
currentButton.append(freeCallForm);
currentButton.existsFreeCall = true;
}
}
$('.main-btn').on('mouseover', showForm);
In this code the same form moves from one to another button without copying and multiple appending.

How to "reset" the .replaceWith function in jQuery?

How do I "reset" the .replaceWith function so that the html, css and javascript are returned back to their original state?
The idea is to have an icon replace the text when the user clicks on "contact", and when the user clicks on "back" button, the icon returns back to the "contact" text. Right now, the icon switches back to text, but the text isn't responsive when I try to repeat the function a second time.
Here is the HTML:
<div class="contact">Contact</div>
<button class="back">Back</button>
And the Javascript:
var contactswitch = $('<div class="icon"><i class="fa fa-facebook"></i></div>');
var switchback = $('.contact');
$('.contact').click(function() {
$(this).replaceWith(contactswitch)
});
$('.back').click(function() {
$(contactswitch).replaceWith(switchback)
});
Thanks!
I think you need to re-assign the click handler on the back button click:
$('.back').click(function() {
switchback.click(function() { $(this).replaceWith(contactswitch);});
$(contactswitch).replaceWith(switchback)
});

Code is taking effect when it shouldn't be

I have a function where if the user clicks on a button, it will display a value in the textbox and it will perform a trigger to another function after a '#btn' button is clicked:
function addwindow(numberAnswer, gridValues, btn) {
$('#mainNumberAnswerTxt').val(numberAnswer).data('data-ignore',true);
$('#btn'+gridValues).trigger('click');
}
Now what I want to do is that:
if the user clicked on the "Add" button, then display the number from the "Number of Answers" column into the textbox or in other words perform this from the addwindow() function:
$('#mainNumberAnswerTxt').val(numberAnswer).data('data-ignore',true);
If the user has clicked on a #btn+gridValues button, then display the number in the textbox of the number of buttons which are currently turned on or in other words perform this code:
if ($('#mainNumberAnswerTxt').data('data-ignore') != true) {
$('.answertxt', context).val(context.find('.answerBtnsOn').length > 0 ? context.find('.answerBtnsOn').length : 0);
}
The problem is that step 1 works fine, it does display the number from the "Number of Answers" column in the textbox after the user has clicked on the "Add" button.
The problem is step 2, it is not displaying the correct number on how many buttons are currently turned on after the user has clicked on the #btn+gridValues button.It just doesn't change the number in the textbox.
Does anyone know why this is happening and how thi can be fixed?
DEMO:
Here is a demo of the application. Please follow the steps below:
Step 1: On left hand side you will see a green plus button, click on it and it opens up a modal window.
Step 2: In modal window there is a search bar, type in "AAA" and submit search, you will see a bunch of rows appear.
Step 3: In the last row, you see under "Number of Answer" colum that it contains the number 4, click on the "Add" button within this row, the modal window will close.
You will see that the textbox displays the number 4 in the textbox which is fine as that was the number within the row under the "Number of Answers" column when you added the row.
But below is the problem:
Step 4: If you click on the "Open Grid" link and select button 3, you will see the letter buttons below change to A-C with only letter "B" turned on.
In the textbox it should display number 1 as only 1 button is turned on, but it doesn't display this number and that is the problem I am having.
How can this problem be fixed?
The problem comes from the fact taht you're setting the data-attribute to false on the $('#mainNumberAnswerTxt') but you're checking against the inputs (this in the click).
One solution would be to do the following test if ($('#mainNumberAnswerTxt').attr('data-ignore') != true)
EDIT
To ensure that the ignore process execute only once (when the grid is reloaded after the modal), you'll have to change what's inside the block after the test:
if ($('#mainNumberAnswerTxt').data('ignore') != true) {
$('.answertxt', context).val(context.find('.answerBtnsOn').length > 0 ? context.find('.answerBtnsOn').length : 0);
} else {
/*reset the ignore flag*/
$('#mainNumberAnswerTxt').data('ignore',false);
}
EDIT2
The main problem is that your reaffecting the $('#mainNumberAnswerTxt').val(numberAnswer) after setting it. Your trying to ignore it through the ignoreattribute.
What i would adivse, would be to remove every occurence to that attribute and to change the following function
function addwindow(questionText,textWeight,numberAnswer,gridValues,reply,btn) {
var answers = $.map(btn.split(''),function(chr){ return "#answer"+chr; }).join(', ');
if($(plusbutton_clicked).attr('id')=='mainPlusbutton') {
var myNumbers = {};
myNumbers["A-C"] = "3";
myNumbers["A-D"] = "4";
myNumbers["A-E"] = "5";
myNumbers["A-F"] = "6";
myNumbers["A-G"] = "7";
gridValues = myNumbers[gridValues];
$('#mainNumberAnswerTxt').show();
$('#mainNumberAnswerTxt').val(numberAnswer).data('ignore',true);
$('#mainGridTxt').val(gridValues).parent().append($('.optionTypeTbl'));
$('#btn'+gridValues).trigger('click');
$('.answers.answerBtnsOn').removeClass('answerBtnsOn').addClass('answerBtnsOff');
$(answers).addClass("answerBtnsOn").siblings().addClass('answerBtnsOff');
}
$.modal.close();
return false;
}
to :
function addwindow(questionText,textWeight,numberAnswer,gridValues,reply,btn) {
var answers = $.map(btn.split(''),function(chr){ return "#answer"+chr; }).join(', ');
if($(plusbutton_clicked).attr('id')=='mainPlusbutton') {
var myNumbers = {};
myNumbers["A-C"] = "3";
myNumbers["A-D"] = "4";
myNumbers["A-E"] = "5";
myNumbers["A-F"] = "6";
myNumbers["A-G"] = "7";
gridValues = myNumbers[gridValues];
$('#mainNumberAnswerTxt').show();
$('#mainGridTxt').val(gridValues).parent().append($('.optionTypeTbl'));
$('#btn'+gridValues).trigger('click');
/* moved the following line below the click simulation,
hence its value will be changed regardless of what happened during the click simulation*/
$('#mainNumberAnswerTxt').val(numberAnswer);
$('.answers.answerBtnsOn').removeClass('answerBtnsOn').addClass('answerBtnsOff');
$(answers).addClass("answerBtnsOn").siblings().addClass('answerBtnsOff');
}
$.modal.close();
return false;
}
In order to modify the value after the visual changes took place.
Use data instead of attr - attr takes a string, data takes JavaScript objects.

Categories

Resources