Check if text is being entered in input using Javascript/jQuery - html

I am trying to hide a placeholder while the input is being used and while there's text inside the input. Here's a simplified version of the HTML for the input and placeholder:
<div id="search-placeholder"><span class="fa fa-search"></span> Search</div>
<input id="search-input" type="text" name="search" />
I tried using jQuery but it does not return the desired result:
$(document).ready(function(){
$('#search-input').focus(function(){
$('#search-placeholder').fadeOut(100);
}).focusout(function(){
$('#search-placeholder').fadeIn(100);
});
});
The placeholder will hide when the input is selected, as it should. But it will show again when the user clicks elsewhere, even while the input is not empty! The placeholder is visible on top of the input value, so I tried a different approach:
$('#search-input').change(function(){
if($('#search-input').val() = '') {
$('#search-placeholder').fadeIn(100);
}else{
$('#search-placeholder').fadeOut(100);
}
})
Unfortunately, this only works when the user clicks elsewhere. The placeholder still shows while typing and while the input is selected, again showing itself on top of the input value. How do I hide <div id="search-placeholder"> while <div id="search-input"> is not empty, or when the input is selected by clicking or tapping it (on focus)?

Maybe try to check the value of the input in the focusout event and only show the placeholder if it's empty:
$(document).ready(function(){
$('#search-input').focus(function(){
$('#search-placeholder').fadeOut(100);
}).focusout(function(){
if($('#search-input').val() === '')
{
$('#search-placeholder').fadeIn(100);
}
});
});
I think you could extract the $('#search-input') and $('#search-placeholder') elements to variables, so the code becomes a bit more readable.

You do this using javascript and jquery
jquery :-
$(document).ready(function(){
$('#search-input').focus(function() {
$('#search-placeholder').fadeOut(100);
});
$('#search-input').focusout(function() {
if($('#search-input').val() === '') {
$('#search-placeholder').fadeIn(100);
}
});
});
javascript
var searchInput = document.getElementById("search-input");
var searchPlaceholder = document.getElementById("search-placeholder");
searchInput.onfocus = function() {
searchPlaceholder.style.display = "none";
}
searchInput.onfocusout = function() {
if(this.value == "") {
searchPlaceholder.style.display = "block";
}
}
if you want to add fade-in fade-out transitions in javascript method use css transition property- transition: opacity 1s and instead of changing style.display change style.opacity to 1(show) and 0(hide)

Related

Replacing text with jQuery only in active/focussed input-Element

I have a page where I have around 10 input-Elements. Some of them I gave the class .no-whitespace-allowed. Now I have a jQuery script running in the background with the purpose to avoid whitespaces in the very input-Elements:
$(function() {
var elements = $(".no_whitespace_allowed");
var func = function() {
if (elements.is(':focus')) elements.val(elements.val().replace(/\s/g, ''));
else elements.val(elements.val());
}
elements.keyup(func).blur(func);
});
However, it replaces the text in every input field with the result that I have the same text in all inputs. Any ideas?
$(".no_whitespace_allowed").keyup(function(){
$(this).val( $(this).val().replace(/\s/g, '') );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="no_whitespace_allowed" type="text">
Something like this ?

How to use nested conditions for displaying a hidden block using angular js

I am trying to put conditions for displaying a hidden div. I want that after entering some value in 'name' textbox and if we click on search link then the hidden block should appear. But in my code, if we click on search link first then enter any value in textbox then also the hidden div is appearing. But I need that only after entering value in textbox , if we click on search then only hidden div should appear.
Iam using below code for hiding the div-
<div ng-show="name.length>0 && IsVisible">
and in script I am writing this code-
$scope.isVisible = false;
$scope.ShowHide = function () {
//If DIV is hidden it will be visible and vice versa.
$scope.IsVisible = true;
}
I have created a plunker here-
https://plnkr.co/edit/oVwZONrn4gtQs1BaiMbO?p=preview
Can any one help me how can I achieve this?
You should add a condition in the method ShowHide itself:
$scope.ShowHide = function () {
if($scope.name) {
//If DIV is hidden it will be visible and vice versa.
$scope.IsVisible = true;
}
}
If you wish the hidden section to be visible only when 'Search' is clicked, then make changes as per following in the HTML file:
<div ng-show="IsVisible">
Refer to the demo here
Check this plnkr. Added a watch on name change:
<input type="text" name="name" class="form-control" ng-change="resetShowHide()" ng-class="" ng-model="name" required/>
and if the name length is 0, reset is IsVisible
$scope.resetShowHide = function(){
if($scope.name.length) $scope.IsVisible = false;
}

Required Attribute Not work in Safari Browser

I have tried following code for make the required field to notify the required field but its not working in safari browser.
Code:
<form action="" method="POST">
<input required />Your name:
<br />
<input type="submit" />
</form>
Above the code work in firefox. http://jsfiddle.net/X8UXQ/179/
Can you let me know the javascript code or any workarround? am new in javascript
Thanks
Safari, up to version 10.1 from Mar 26, 2017, doesn't support this attribute, you need to use JavaScript.
This page contains a hacky solution, that should add the desired functionality: http://www.html5rocks.com/en/tutorials/forms/constraintvalidation/#toc-safari
HTML:
<form action="" method="post" id="formID">
<label>Your name: <input required></label><br>
<label>Your age: <input required></label><br>
<input type="submit">
</form>
JavaScript:
var form = document.getElementById('formID'); // form has to have ID: <form id="formID">
form.noValidate = true;
form.addEventListener('submit', function(event) { // listen for form submitting
if (!event.target.checkValidity()) {
event.preventDefault(); // dismiss the default functionality
alert('Please, fill the form'); // error message
}
}, false);
You can replace the alert with some kind of less ugly warning, like show a DIV with error message:
document.getElementById('errorMessageDiv').classList.remove("hidden");
and in CSS:
.hidden {
display: none;
}
and in HTML:
<div id="errorMessageDiv" class="hidden">Please, fill the form.</div>
The only drawback to this approach is it doesn't handle the exact input that needs to be filled. It would require a loop accross all inputs in the form and checking the value (and better, check for "required" attribute presence).
The loop may look like this:
var elems = form.querySelectorAll("input,textarea,select");
for (var i = 0; i < elems.length; i++) {
if (elems[i].required && elems[i].value.length === 0) {
alert('Please, fill the form'); // error message
break; // show error message only once
}
}
If you go with jQuery then below code is much better. Just put this code bottom of the jquery.min.js file and it works for each and every form.
Just put this code on your common .js file and embed after this file jquery.js or jquery.min.js
$("form").submit(function(e) {
var ref = $(this).find("[required]");
$(ref).each(function(){
if ( $(this).val() == '' )
{
alert("Required field should not be blank.");
$(this).focus();
e.preventDefault();
return false;
}
}); return true;
});
This code work with those browser which does not support required (html5) attribute
Have a nice coding day friends.
I had the same problem with Safari and I can only beg you all to take a look at Webshim!
I found the solutions for this question and for this one very very useful, but if you want to "simulate" the native HTML5 input validation for Safari, Webshim saves you a lot of time.
Webshim delivers some "upgrades" for Safari and helps it to handle things like the HMTL5 datepicker or the form validation. It's not just easy to implement but also looks good enough to just use it right away.
Also useful answer on SO for initial set up for webshim here! Copy of the linked post:
At this time, Safari doesn't support the "required" input attribute. http://caniuse.com/#search=required
To use the 'required' attribute on Safari, You can use 'webshim'
1 - Download webshim
2 - Put this code :
<head>
<script src="js/jquery.js"></script>
<script src="js-webshim/minified/polyfiller.js"></script>
<script>
webshim.activeLang('en');
webshims.polyfill('forms');
webshims.cfg.no$Switch = true;
</script>
</head>
I have built a solution on top of #Roni 's one.
It seems Webshim is deprecating as it won't be compatible with jquery 3.0.
It is important to understand that Safari does validate the required attribute. The difference is what it does with it. Instead of blocking the submission and show up an error message tooltip next to the input, it simply let the form flow continues.
That being said, the checkValidity() is implemented in Safari and does returns us false if a required filed is not fulfilled.
So, in order to "fix it" and also show an error message with minimal intervention (no extra Div's for holding error messages) and no extra library (except jQuery, but I am sure it can be done in plain javascript)., I got this little hack using the placeholder to show standard error messages.
$("form").submit(function(e) {
if (!e.target.checkValidity()) {
console.log("I am Safari"); // Safari continues with form regardless of checkValidity being false
e.preventDefault(); // dismiss the default functionality
$('#yourFormId :input:visible[required="required"]').each(function () {
if (!this.validity.valid) {
$(this).focus();
$(this).attr("placeholder", this.validationMessage).addClass('placeholderError');
$(this).val(''); // clear value so it shows error message on Placeholder.
return false;
}
});
return; // its invalid, don't continue with submission
}
e.preventDefault(); // have to add it again as Chrome, Firefox will never see above
}
I found a great blog entry with a solution to this problem. It solves it in a way that I am more comfortable with and gives a better user experience than the other suggestions here. It will change the background color of the fields to denote if the input is valid or not.
CSS:
/* .invalid class prevents CSS from automatically applying */
.invalid input:required:invalid {
background: #BE4C54;
}
.invalid textarea:required:invalid {
background: #BE4C54;
}
.invalid select:required:invalid {
background: #BE4C54;
}
/* Mark valid inputs during .invalid state */
.invalid input:required:valid {
background: #17D654 ;
}
.invalid textarea:required:valid {
background: #17D654 ;
}
.invalid select:required:valid {
background: #17D654 ;
}
JS:
$(function () {
if (hasHtml5Validation()) {
$('.validate-form').submit(function (e) {
if (!this.checkValidity()) {
// Prevent default stops form from firing
e.preventDefault();
$(this).addClass('invalid');
$('#status').html('invalid');
}
else {
$(this).removeClass('invalid');
$('#status').html('submitted');
}
});
}
});
function hasHtml5Validation () {
return typeof document.createElement('input').checkValidity === 'function';
}
Credit: http://blueashes.com/2013/web-development/html5-form-validation-fallback/
(Note: I did extend the CSS from the post to cover textarea and select fields)
I use this solution and works fine
$('#idForm').click(function(e) {
e.preventDefault();
var sendModalForm = true;
$('[required]').each(function() {
if ($(this).val() == '') {
sendModalForm = false;
alert("Required field should not be blank."); // or $('.error-message').show();
}
});
if (sendModalForm) {
$('#idForm').submit();
}
});
The new Safari 10.1 released Mar 26, 2017, now supports the "required" attribute.
http://caniuse.com/#search=required
You can add this event handler to your form:
// Chrome and Firefox will not submit invalid forms
// so this code is for other browsers only (e.g. Safari).
form.addEventListener('submit', function(event) {
if (!event.target.checkValidity()) {
event.preventDefault();
var inputFields = form.querySelectorAll('input');
for (i=0; i < inputFields.length; i++) {
if (!inputFields[i].validity.valid) {
inputFields[i].focus(); // set cursor to first invalid input field
return false;
}
}
}
}, false);
Within each() function I found all DOM element of text input in the old version of PC Safari, I think this code useful for newer versions on MAC using inputobj['prpertyname'] object to get all properties and values:
$('form').find("[required]").each(function(index, inputobj) {
if (inputobj['required'] == true) { // check all required fields within the form
currentValue = $(this).val();
if (currentValue.length == 0) {
// $.each((inputobj), function(input, obj) { alert(input + ' - ' + obj); }); // uncomment this row to alert names and values of DOM object
var currentName = inputobj['placeholder']; // use for alerts
return false // here is an empty input
}
}
});
function customValidate(){
var flag=true;
var fields = $('#frm-add').find('[required]'); //get required field by form_ID
for (var i=0; i< fields.length;i++){
debugger
if ($(fields[i]).val()==''){
flag = false;
$(fields[i]).focus();
}
}
return flag;
}
if (customValidate()){
// do yor work
}

multistep form - toggle between styled radio buttons

i have built a multi step form that works , but it is not very "elegant" coded,
so i am asking
for your advice to make it more efficient ,
i have placed here only 2 steps out of 3 because the first step - email name etc', is not relevant for my question:
in each step 2 and 3 there are 2 styled radio button yes and no for the user to select,
in each step i need to toggle between check and uncheck styled images and of course prevnt that both
yes and no check images will show at the same time.
i know that the default/not styled radio buttons behavior prevents two checked buttons at the same time- can i use it here to save some lines of code?
the html(index.php)
<form method="post" id="userForm" action="process_form.php">
<fieldset class="formFieldset">
<div id="second_step" class="vanish">
<div class="form slide_two check_wrap">
<div class="quizyes quizbtn">
<img class="uncheck_pic pic one" src="images/check_not.png">
<img class="check_pic pic agree" src="images/check_bgfull.png" style="display: none;">
<h1 class="quizText">yes</h1>
</div>
<div class="quizno quizbtn">
<img class="uncheck_pic pic two" src="images/check_not.png">
<img class="check_pic not not_agree pic first_not" src="images/check_bgfull.png" style="display: none;">
<h1 class="quizText">no</h1>
</div>
<div id="feedback_wrap"><div class="feedback"></div></div>
<div id="submit_wrap" >
<input type="radio" class="yep decideOne" val ="1" name="yep" style="display: none;"/>
<input type="radio" class="nope decideOne" val ="2" name="nope" style="display: none;"/>
</div>
</div></div>
<!-- end of second step -->
<!-- third step -->
<div id="third_step" class="vanish">
<div class="form check_wrap">
<div class="quizyes quizbtn">
<img class="uncheck_pic pic one" src="images/check_not.png">
<img class="check_pic pic agree" src="images/check_bgfull.png" style="display: none;">
<h1 class="quizText">yes</h1>
</div>
<div class="quizno quizbtn">
<img class="uncheck_pic pic two" src="images/check_not.png">
<img class="check_pic not not_agree pic second_not" src="images/check_bgfull.png" style="display: none;">
<h1 class="quizText">no</h1>
</div>
<div id="feedback_wrap"><div class="feedback"></div></div>
<div id="submit_wrap">
<input type="radio" class="yep decideTwo" val ="1" name="yep" style="display: none;"/>
<input type="radio" class="nope decideTwo" val ="2" name="nope" style="display: none;"/>
</div>
</div></div>
<!-- end of third step -->
</fieldset>
<div id="submit_wrap">
<input class="submit btn" type="button" name="submit_all" id="submit_all" value="" />
</div>
</form>
the script
$(document).ready(function(){
$(function() {
$('.check_pic').hide();
//original field values
var isDecide= false;
//toggle images and set values
$('.pic').on('click', function(event) {
if ($(this).hasClass('uncheck_pic') && $(this).hasClass('one') ){
$(".yep").val('agree');
$(this).hide();
$(this).siblings('.check_pic').show();
$(".not").hide();
$(".two").show();
}
else if ($(this).hasClass('uncheck_pic') && $(this).hasClass('two') ){
var isDecide = $(".nope").val('notagree');
$(this).hide();
$(this).siblings('.check_pic').show();
$('.agree').hide();
$(".one").show();
}
else if ($(this).hasClass('check_pic') && $(this).hasClass('agree') ){
$(this).hide();
$(this).siblings('.uncheck_pic').show();
}
else if ($(this).hasClass('check_pic') && $(this).hasClass('not_agree') ){
$(this).hide();
$(this).siblings('.uncheck_pic').show();
}
});
// start the submit thing
$('#submit_all').click(function() {
if($('#second_step').is(":visible")) {
$('.decideOne').removeClass('error valid');
// prevent empty boxes and display a message
if($('.one').is(":visible") && $('.two').is(":visible")) {
$('.feedback').text('please select one').show();
return false;
}
// case the user selects yes
if($('.agree').is(":visible")) {
$('.feedback').text('thank you for selecting yes').show();
var isDecide = $(".yep").val();
var name = $("#firstname").val();
var phone = $("#phone").val();
var email = $("#email").val();
var dataString = 'user-details:name=' + name + ' phone=' + phone + ' email=' + email + ' decide=' + isDecide ;
$.ajax({
type : "POST",
url : "/",
data: dataString,
success : function(data) {
console.log('data');
$('#second_step').delay(1000).fadeOut(600, function() {
$('#first_step').fadeIn(400);
$('.feedback').hide();
});
}
});
}
// case the user selects no
if($('.first_not').is(":visible")) {
$(".yep").val();
$(".nope").val();
$('#second_step').fadeOut(600, function() {
$('#third_step').fadeIn(600);
$('.feedback').hide();
});
}
return false;
// end second step
} else if($('#third_step').is(":visible")) {
$('.third_input').removeClass('error').removeClass('valid');
// prevent empty boxes and display a message
if($('.quizyes .one').is(":visible") && $('.quizno .two').is(":visible")) {
$('.feedback').text('please select one').show();
return false;
}
// if decide yes then submit
if($('.agree').is(":visible")) {
$('.feedback').text('thank you for selecting yes').show();
var isDecide = $(".yep").val();
var name = $("#firstname").val();
var phone = $("#phone").val();
var email = $("#email").val();
var dataString = 'user-details:name=' + name + ' phone=' + phone + ' email=' + email + ' decide=' + isDecide ;
$.ajax({
type : "POST",
url : "/",
data: dataString,
success : function(data) {
console.log('data');
$('#second_step').delay(1000).fadeOut(600, function() {
$('#first_step').fadeIn(400);
$('.feedback').hide();
});
}
});//end ajax
return true;
}//end if agree is visible
// if decide no then send message and quit
if($(".second_not").is(":visible")) {
$(".nope").val("no");
$('.feedback').text('too bad bye bye').show();
$('#third_step').fadeOut(3000, function() {
$('#first_step').fadeIn(600);
$('.feedback').hide();
});
}
}
// end third step
});
//end submit_all
}) // general function
}); // document ready
Dude my wish to you take a look on good js library - knockout to represants all that kind show, hide functunality and forms inputs, checkbox, radiobutton modifications.
If you're using images to style your radiobuttons I would suggest combining the images into a Sprite and just using css to move the background-position of the image using the input[type=radio]:checked selector. No javascript necessary.
For Example - you combine your two images into a single image that is 100px wide, each individual image being 50px wide. And then style the checkbox...
input[type=radio].myCustomRadioButton {
background: url(myRadioButtonSprite.png) 0 0;
}
input[type=radio].myCustomRadioButton:checked {
background-position: -50px 0;
}
Assuming your images are lined up horizontally in your sprite, this would move the background image of the radiobutton left 50px to display the checked-image, when the radiobutton is checked.
As a side note, doing this is going to require unsetting some of the browser styling that is going to occur automatically. A good reset for form elements is to start with these styles.
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
Keep in mind if you need to support Internet Explorer versions less than 9, the :checked pseudo-selector isn't available in pure CSS and you may need to resort to some scripting.
Listen for the change event on your custom radio buttons and update a parent element based on that.
Here's an example.
The <input> has position: absolute so the clip property can be applied to hide it and it does not affect the content box of its parent, which has relative position to contain it.
I used background-color but you could swap this in for your image urls or change the background-position of a sprite as suggested in rob-gordon's answer.
You can still add visible label text inside the label as you see in the second set of radio inputs.

jQuery Radio Button Image Swap

I am essentially brand new to coding (html5 forms, CSS3 and now jQuery).
What I am trying to do is have an imageswap (which I have done) attached to a radio button. So what I'm doing is replacing the buttons with images, each with a "pressed" version. However, before even attaching it to a form function/radio button input, I want to find a way so that when I click one button, it switches the other images back to "un-pressed". Essentially so that only one image can be "pressed" at a time.
Right now the code for me pressed images are
$(function() {
$(".img-swap1").live('click', function() {
if ($(this).attr("class") == "img-swap1") {
this.src = this.src.replace("_U", "_C");
} else {
this.src = this.src.replace("_C","_U");
}
$(this).toggleClass("on");
});
});
I thought about using an if statement to revert all the "_C" (clicked) back to "_U" (unclicked).
Hopefully I've included enough information.
A good pattern for solving this problem is to apply the unclicked state to ALL your elements, then immediately afterward apply the clicked state to the targeted element.
Also, your if statement ($(this).attr("class") == "img-swap1") is redundant -- it will always be true because it's the same as the original selector $(".img-swap1").live('click'...
Try
$(function() {
$(".img-swap1").live('click', function() {
$(".img-swap1").removeClass('on').each(function(){
this.src = this.src.replace("_U", "_C");
});
this.src = this.src.replace("_C","_U");
$(this).addClass("on");
});
});
If I understand the question correctly the following may work for you:
$(function(){
$('.img-swap1').live('click', function() {
$('.img-swap1').removeClass('on').each(function(){
$(this).attr('src', $(this).attr('src').replace("_C", "_U")); // reset all radios
});
$(this).attr('src', $(this).attr('scr').replace("_U", "_C")); // display pressed version for clicked radio
$(this).toggleClass("on");
});
});
I hope this helps.