jQuery: toggling attribute within a toggleClass function - javascript

I'm trying to add an attribute to a searchfield only when it is visible, so I have the following code to a) hide the search form initially, b) toggle the visibility and c) add or remove the attribute "autofocus" to the form's input when the form is given the class "focus" (e.g being visible). The code for a) and b) works as it should, c) is my imagined take on how the addAttr() thing should be, but I don't really know Javascript so obviously it's not working. The question is: How do I make it work?
$("#searchwdgt").hide();
$(function() {
$('#show_search').click(function() {
$('#show_search').toggleClass('active');
$('#searchwdgt').toggleClass('focus').slideToggle(400);
if($('#searchwdgt.focus')) {
$('#searchwdgt input').addAttr('autofocus');
} else {
$('#searchwdgt input').removeAttr('autofocus');
}
return false;
});
});
The basic construct is simple. #show_search is an anchor that the user clicks to get the search form (#searchwdgt). To minimize the number of user clicks it would be nice if the attribute "autofocus" could be added to the input (has class "searchfield", is type "search", just for clarification) when the form becomes visible, but for UX purposes it can't be in place always (this messes with tab browsing since the form is hidden initially). So, any constructive pointers that can help solve the issue are most welcome. Thanks.

the function should be
.attr('autofocus','autofocus')
instead of
.addAttr('autofocus');
The reason it isn't working is that each attribute needs to have a value, even if it's null

Related

Show div when click on a different div, and show a different div when clicked again

I currently have made a way so the user can add another text field to the form by pressing on a 'add_another' div, this uses basic JS so when the user presses on the div 'add_another' the div 'author_2' is toggled.
I would like to make it so that when the user presses on the 'add_another' div for a second time it shows 'author_3' div, and when they press 'add_another' again, it then shows 'author_4'. I have put all the CSS and HTML divs in place to support this, I am just trying to adapt my code so it shows one div after another, rather then toggling a single div.
Here is my JS:
<script>
$(document).ready(function() {
$('.add_another').on('click', function(){
$('.author_2').toggle();
});
});
</script>
I have tried altering this code, however with no luck.
I haven't added my HTML as it is just 4 divs, 'author_1' 'author_2' ... 3...4
Thankyou for your help
There are two solutions to Your problem.
First one - use static code
It means the max author count is 4 and if user gets to 4, this is it.
If so - You need to store the number of authors already shown.
var authors_shown = 1;
$(document).ready(function() {
$('.add_another').on('click', function(){
authors_shown++;
if (!$('.author_'+authors_shown).is(":visible")) {
$('.author_'+authors_shown).toggle();
}
});
});
But there is also a second - more dynamic option.
What if user wants to input 10 or 20 authors? You don't want to pre render all that html code and hide it. You should clone the div and change its id or if the (HTML) code (for another author) is not too long, you can render it within JS code.
var div = document.getElementById('div_id'),
clone = div.cloneNode(true); // true means clone all childNodes and all event handlers
clone.id = "some_id";
document.body.appendChild(clone);
If it's a form, then change names of input fields to array as author_firstname[]
Also You can store number of added authors in another hidden field (so you know how long to loop the form fields on the server side.
The second option is a bit more complex and longer, but way more dynamic.
You should make another div when clicked on add_another:
something like this:
<script>
$(document).ready(function() {
$('.add_another').on('click', function(){
$('<div><input type="text" name="name[]" /></div>').appendTo('.your_container');
});
});
</script>
as you see, input's name has [] which means you should treat with the inputs as an array.
let me know if you got any further questions
good luck.

jQuery For Loop Image Check and Display

Good afternoon Stack Overflow,
I'm inexperienced when it comes to coding in general and I've been having a problem that's doing my head in!
If you'll allow me to set the scene...
The section of the project I am currently working on involves a user picking items from a warehouse in order to fulfil a shipment and in some cases they have to pick the same item from various locations, when that needs to be done, the small "!" type icon appears next to the item.
The user then can click on the icon and choose which locations they will be retrieving the stock from, they then press confirm on the modal and when it closes it sets the text back to blue and hides the icon.
The part I am having trouble with is that once all the locations have been established, the order needs to be processed and this requires a button to be clicked on, which I only want to appear once all the "!" icons are hidden.
I know there are alot of questions based on for loops and images checks and believe me when I say I've tried hard to figure this out myself and I've tried different approaches:
ShowProcess = false
for (i = 0; i<Picker; i++) {
if ($('#MultiLocIcon'+i).is(':visible')){
ShowProcess = true
}
if (ShowProcess == true) {
$('#ProcessConfirm').show()
};
};
This obviously wouldn't work because its setting the first variable in the list to "true" and will always read it as true, therefore always showing the image, even if the "!" icon still exists in other rows.
I also tried using .each() to test each rows text color of a specific but also had no luck:
var table = $('#RequestedItemsTable');
table.find('tbody > tr').each(function(){
if $('#Desc').css('color') == '#0000FF'){
//do something
I feel like my experience is letting me down as I still have a lot to learn and have a suspicious feeling that the solution is going to be really easy, but then again, its only easy if you know how.
If anyone could take the time to help me with this problem or offer me any advice, I'd be really grateful.
Here is a section of my code which might be useful:
Modal "Confirm" button:
//CONFIRM Button which will submit final picks.
'Confirm': function() {
//Reset the length loop
length = undefined;
//Remove "Multiple Location" icon from the row.
$('#icon'+id).hide();
//Change text colour back to blue to have visual confirmation that item is ready for picking
$('#Desc'+id).css('color', '#0000FF');
$('#QtyReq'+id).css('color', '#0000FF');
$('#QtyinStock'+id).css('color', '#0000FF');
$(this).dialog('close');
The "!" Icon:
<td id= "MultiLocIcon<?=$i;?>"><?if($row->Count_Location > 1)
{?><img src="<?=base_url();?>public/css/images/error.png" alt="LocPick" title="Multiple Locations" style="cursor: pointer;" id= "icon<?=$i;?>" onClick="$.LocPick(<?=$i;?>);"/><?}?></td>
Basically just need to know how my image can show once the loop checks and knows that the "!" icon is hidden from every possible row.
Thank you for your patience.
You'll need to add a second check in your modal logic, perhaps after your .hide():
//Remove "Multiple Location" icon from the row.
$('#icon'+id).hide();
$('img[id^=icon]:visible').length || $('#ProcessConfirm').show();
What this does is combines the :visible pseudo-selector and a regex selector for all img tags with id starting with "icon". This assumes you won't have any other unrelated image tags with an id like "icon*". If the length is 0, it will go ahead and show the #ProcessConfirm element.
simplest solution I would give is to add a class warning to all the table column which has warning icon & then check for visibility of the same.
if($('.warning:visible').length === 0){
//all warning icons are hidden
}
What I would do is based off your HTML, select all the alert icons, and do a :visible psuedo selector on it. This will return all the visible alert icons, if there are none in the array, you know none of them are visible. You will need to identify them with a class, such as .alert:
if( $(".alert:visible").length === 0 ){
// Do your code in here for no visible alert icons!
}
When user clicks confirm on modal you should run a check on how many icons are still visible, and if the amount is 0 then show the button, like this:
// This searchs for every <td> with an id that contains '#MultiLocIcon'
// Then checks if the amount of those which are visible is 0 and do something
if ( $('td[id*=MultiLocIcon]').not(':visible').length === 0 ) {
$('#ProcessConfirm').show()
}

check box validation javascript

I need to validate the selection of at least one check box on a table. I am not using an alert because I already have a class on CSS that highlights in red the inputs, selects and other elements if they are not filled out.
This is my JS:
var btnRegister= document.querySelector('#btnRegisterRegObr');
btnRegister.addEventListener('click', function () {
var bError= false;
//I am initializing this boolean variable so that it also shows an error
//message on the screen if the user has not selected any option at all...
var elementCheckRegObr = document.querySelector('#checkRegObr');
if (elementCheckRegObr.checked==false){
bError=true;
elementCheckRegObr.classList.add('error');
//This part of the code brings the error I have
//previously created on CSs if the checkbox is not checked
}
else{
elementCheckRegObr.classList.remove('error');
}
});
The button on HTML has the right id on the HTML: id="btnRegisterRegObr.
I was looking at some codes here and people were validating using the .checked==false
However this does not seem to work for mine.
As a matter of fact, I first thought I needed to use the syntax of if (elementCheckRegObr.checked=="") but that one does not seem to work either.
I dont have problems validating inputs, selects nor radio buttons, but I am not sure if I am doing it on the right way with the check boxes. Any help or advice would be greatly apprecciate it :)
I suggest that you use getElementById to get your elements, and test if the checkbox is checked this way:
if(document.getElementById('idOfTheCheckBox').checked){
alert('hey, im checked!');
}

Insert input if it does not exist

I am working on an email template editor where the user will select from a list of pre-existing templates and will be able to update the template as necessary. I had problems with using the CKEditor plugin across browsers and so I have attempted to create my own. When the user selects a template it opens in a modal window. To change the images I have included input tags which are removed upon close of the modal. This works so well and so good but if the user then wants to go back into the editor the input buttons are no longer there.
I want to add in the input button in the modal window if it does not exist. I have tried checking the length of the property but I am unable to return a value other than null whether it exists or not. My code is as follows:
function template1InputButtons() {
if ($("#imageInput1T1").length == 0) {
$('<input id="imageInput1T1" type="file" name="newImage1T1" onchange="previewImage1T1(this)" />').insertBefore('.article_media');
}
}
If I open it the first time the length comes up as one and so nothing is added as expected. If I remove and then click the button again length shows as 0 and input is added correctly as expected. If I then remove the input and click the button again the length comes up as 1 despite the control not existing.
Any ideas?
Try this:
function template1InputButtons() {
if (!$("#imageInput1T1")) {
$('<input id="imageInput1T1" type="file" name="newImage1T1" onchange="previewImage1T1(this)" />').insertBefore('.article_media');
}
}
and also assure that you have placed it inside ready function.
Try this:
if ($("body").find("#imageInput1T1").length == 0) {
$('<input id="imageInput1T1" type="file" name="newImage1T1" onchange="previewImage1T1(this)" />').insertBefore('.article_media');
}
Problem was a similar finding of class attribute article_media on the other modal my mistake thanks for the help anyway

value from dropdown show/hides div and keeps its state

im relatively new to ROR, and would like some help with the following code.
I would like to show a div (it's called demographics) when a specific selection ("Customers") is made form a dropdown. If an option other than "Customers" is selected from the dropdown, I would like that the demographicsv div remain hidden.
At present, my code is partially working. It shows and hides the div; however, when I save the page and come back to it, the div is hidden, even if "Customers" is selected in the dropdown. This might be because the default setting is: display:none.
Is there a way to make sure that the field is displayed on page load when the proper selection has been made?? And I suppose a way to make the opposite true too--> a div with display:block; remains hidden if the field from the dropdown does not match the required field.
Any help would be extremely appreciated. Thank you and I sincerely appreciate your time:
my code (HAML):
= f.select :who, WHO, {}, :onChange => "showDemographics(this)", :prompt => true
#demographics{:style => "display:none;"}
%p.information
please fill out the following demographics.
%div{:class => "label_leftalign field"}
= f.label :age, "Age"
= f.select :age, AGES, :prompt => true
%div{:class => "label_leftalign field"}
= f.label :race,
= f.select :race, RACES, :prompt => true
Javascript
function showDemographics(obj)
{
if(obj[obj.selectedIndex].value == 'Customer')
{
document.getElementById('demographics').style.display = 'block';
}
else
{
document.getElementById('demographics').style.display = 'none';
}
}
EDIT::
OK, So the key issue is that on page reload a div remains hidden even if the correct value is in the dropdown box. I suppose that this can be solved by one of two ways 1. running some sort of validation on everytime the page is loaded or 2. cookies.
Unfortunately, I'm not very well versed in Javascript or jQuery... and I've never implemented cookies on a site, and would prefer to avoid using them if possible.
Could anyone help me write a script that validates the presence of Customer in the dropdown and shows/hides a div accordingly? Thank you, and thanks to Carlos Pardilla and M. Cypher for their help thus far.
You have tagged the question with jQuery although you're not using it in the code, but I'll just assume it's fine if I give you some jQuery code:
$(function() {
$('#who').change(function() {
if ($(this).val() == 'Customer') {
$('demographics').show();
} else {
$('demographics').hide();
}
}).change();
}
Note that you need to give the select an id (in this case who) for it to work.
I guess you could use a conditional statement to be checked during page load. You could establish the visibility (or lack thereof) of the div depending on the value ("Customers") of the option:selected element within your select object (the dropdown). Maybe via a script on the head of the document (provided it is a short script). Also, by doing this you wouldn't need to set the display property from the start. It would fire depending on the selected condition during page load.
This could be done to get the opposite result as well, as you said.
Hope it'll help!
The answers above where correct in their own way... the link below shows the actual code that is required for the conditional statement on page load:
show hidden divs on refresh

Categories

Resources