How to keep data-fixedvalue in different textboxes? - javascript

I have two different textboxes and a function to keep some part of values in each of them even if the user deletes textboxes data-fixedvalue will be back .
I worte the below code but this code only works for the first class for the next class it does not consider data-fixedvalue.
How can I fix this issue?
Here is my snippet :
var el = document.querySelector( ".telinfo" );
el.addEventListener( "keyup", handleEv);
el.addEventListener( "blur", handleEv);
function handleEv( event )
{
var thisObj = event.currentTarget;
var fixedValue = thisObj.getAttribute( "data-fixedvalue" );
if ( thisObj.value.indexOf( fixedValue ) != 0 )
{
console.log(thisObj.value, fixedValue);
event.preventDefault();
thisObj.value = fixedValue;
}
}
<input type="text" value="+98912314789" class="telinfo" data-fixedvalue = "+9891" maxlength="13">
<input type="text" value="+7812345678" class="telinfo" data-fixedvalue = "+78">

You were almost there. You have multiple elements so use document.querySelectorAll( ".telinfo" ) and then iterate over all of them (it's an array) with forEach() cause you need to add the event listener to every element you want to handle the event.
var elements = document.querySelectorAll( ".telinfo" );
elements.forEach(function(element){
element.addEventListener( "keyup", handleEv);
element.addEventListener( "blur", handleEv);
});
function handleEv( event ) {
var thisObj = event.currentTarget;
var fixedValue = thisObj.getAttribute( "data-fixedvalue" );
if ( thisObj.value.indexOf( fixedValue ) != 0 ) {
console.log(thisObj.value, fixedValue);
event.preventDefault();
thisObj.value = fixedValue;
}
}
<input type="text" value="+98912314789" class="telinfo" data-fixedvalue = "+9891" maxlength="13">
<input type="text" value="+7812345678" class="telinfo" data-fixedvalue = "+78">

Related

Need to apply AND logic in jquery each function for filtering functionality

I want to implement a multiple filtering functionality in my website. I am having issue with obtaining correct functionality so I would be grateful if I could get help on achieving the correct functionality on applyFilter() function.
SCENARIO: User clicks on single storey, 3 bedrooms, 2 bathrooms buttons in the filter.
EXPECTED: Only products with single-storey having 3 bedrooms and 2 bathrooms should display (AND LOGIC).
CURRENT OP: It display all single-storey, all 3 bedrooms and all 2 bathrooms products (OR LOGIC).
$( document ).ready( function ()
{
var $filters = $( '.works-filter' ); // find the filters
var $works = $( '.workItem' ); // find the portfolio items
var showAll = $( '.showAll' ); // identify the "show all" button
var cFilter, cFilterData; // declare a variable to store the filter and one for the data to filter by
var filtersActive = []; // an array to store the active filters
$filters.click( function ()
{ // if filters are clicked
cFilter = $( this );
cFilterData = cFilter.attr( 'data-filter' ); // read filter value
highlightFilter();
applyFilter();
checkIfNoResults();
} );
function highlightFilter ()
{
var filterClass = 'works-filter-active';
if ( cFilter.hasClass( filterClass ) )
{
cFilter.removeClass( filterClass );
removeActiveFilter( cFilterData );
} else if ( cFilter.hasClass( 'showAll' ) )
{
$filters.removeClass( filterClass );
filtersActive = []; // clear the array
cFilter.addClass( filterClass );
} else
{
showAll.removeClass( filterClass );
cFilter.addClass( filterClass );
filtersActive.push( cFilterData );
}
}
function applyFilter ()
{
// go through all portfolio items and hide/show as necessary
$works.each( function ()
{
var i;
var classes = $( this ).attr( 'class' ).split( ' ' );
if ( cFilter.hasClass( 'showAll' ) || filtersActive.length == 0 )
{ // makes sure we catch the array when its empty and revert to the default of showing all items
$works.addClass( 'show-workItem' ); //show them all
} else
{
$( this ).removeClass( 'show-workItem' );
for ( i = 0; i < classes.length; i++ )
{
if ( filtersActive.indexOf( classes[ i ] ) > -1 )
{
$( this ).addClass( 'show-workItem' );
}
}
}
} );
}
// remove deselected filters from the ActiveFilter array
function removeActiveFilter ( item )
{
var index = filtersActive.indexOf( item );
if ( index > -1 )
{
filtersActive.splice( index, 1 );
}
}
} );
Filter button demo code
<div class="filter-button">
<label class="checkWrap">
<input type="checkbox" data-filter="<?php echo $storey->slug ?>" class=" works-filter
storeyCheck control" name="storeys" value="<?php echo $storey->slug ?>">
<span class="check-span checkmark"> <img src="<?php echo get_template_directory_uri() . $img; ?>"
class="p-5"><?php echo $storey->name; ?>
</span>
</label>
</div>
Container demo code
<div id="projects" class="workItem show-workItem mix <?php echo $storey->slug;?>">
<div class="project-grid ">
</div>
</div>
I used "every" and "includes" function to check compare two arrays.
let checker = ( arr, target ) => target.every( v => arr.includes( v ) );
for ( i = 0; i < classes.length; i++ )
{
if ( checker( classes, filtersActive ) == true)
{
$( this ).addClass( 'show-workItem' );
}
}

how to select singel and multiple checkbox with radiobutton

i'm stuck with this problem. i have 2 radiobutton and few checkbox. what i want to do is if radiobutton1 chacked, it only allow check 1 checkbox, then if radiobutton2 chacked, it will allow all checkbox to be checked.
i've been tried some script, but not any of them work.
this is my code for sample.
HTML
<input type="radio" id="radio1" name="radiobtn1" />
<input type="radio" id="radio1" name="radiobtn2" />
<input type="checkbox" name="cb" value="1" onclick="test(this)" />
<input type="checkbox" name="cb" value="2" onclick="test(this)"/>
<input type="checkbox" name="cb" value="3" onclick="test(this)"/>
<input type="checkbox" name="cb" value="4" onclick="test(this)"/>
<input type="checkbox" name="cb" value="5" onclick="test(this)"/>
script for select only 1 checkbox
function test(id){
var cb = document.getElementsByName("cb");
Array.prototype.forEach.call(cb,function(el){
el.checked = false;
});
id.checked = true;
}
my script
$(function test(id){
$("#radio1, #radio2").change(function(){
if($("#radio1").is(":checked")){
var cb = document.getElementsByName("cb");
Array.prototype.forEach.call(cb,function(el){
el.checked = false;
});
id.checked = true;
}
else if($("#radio2").is(":checked")){
}
});
});
thank you for your help.
it's like your question has been solved.
next time try to find it first.
but you can try this script.
var $form = $('#form1');
var $checkboxes = $('input[type=checkbox]');
var $selectionType = $('input[type=radio]');
var $output = $('#output');
// Used to determine if the Multi radio is selected
var isMulti = false;
// Listen to change event on the radio buttons and set isMulti
$selectionType.on('change', function( e ) {
// Check the value of what radio button was clicked
isMulti = $( e.target ).val() === 'Multi';
// Clear all selected checkboxes if user clicked "single"
if( !isMulti ) {
$checkboxes.each( function( idx, item ) {
$( item ).prop( 'checked', false );
});
}
});
// Listen to clicks on checkboxes
$checkboxes.on('change', function( e ) {
// Store what was just clicked
var $this = $( e.target );
// If Multi is not selected, then remove the check from all checkboxes except
// the one that the user actually clicked on
if( !isMulti ) {
$checkboxes.each( function( idx, item ) {
var $item = $( item );
if( $item.attr('id') === $this.attr('id') ) {
return true;
}
$item.prop('checked', false );
});
}
});
http://jsfiddle.net/grammar/pdx8gccu/2/

How to customize validation message position in login validation?

<input type="text" class="form-control"
name="username" placeholder="Enter ID" required
oninvalid="this.setCustomValidity('Enter ID')"
oninput="setCustomValidity('')" />
How to customize the Validation message position to the right of the textbox? Now it's coming below the textbox.
Plunker link: http://plnkr.co/edit/vvfR5pelzeJAMM5LagC9?p=preview
Using of positions to the element for parent element use relative and use position absolute for tooltip. If possible show your demo code.
Here is an example with jQuery dependent script.
<div>
<label for="name">Name:</label>
<input id="name" type="text" required>
</div>
<div>
<label for="comments">Comments:</label>
<textarea id="comments" required></textarea>
</div>
<div class="buttons">
<button>Submit</button>
</div>
</form>​
<script>
var createAllErrors = function() {
var form = $( this ),
errorList = $( "ul.errorMessages", form );
var showAllErrorMessages = function() {
errorList.empty();
// Find all invalid fields within the form.
var invalidFields = form.find( ":invalid" ).each( function( index, node ) {
// Find the field's corresponding label
var label = $( "label[for=" + node.id + "] "),
// Opera incorrectly does not fill the validationMessage property.
message = node.validationMessage || 'Invalid value.';
errorList
.show()
.append( "<li><span>" + label.html() + "</span> " + message + "</li>" );
});
};
// Support Safari
form.on( "submit", function( event ) {
if ( this.checkValidity && !this.checkValidity() ) {
$( this ).find( ":invalid" ).first().focus();
event.preventDefault();
}
});
$( "input[type=submit], button:not([type=button])", form )
.on( "click", showAllErrorMessages);
$( "input", form ).on( "keypress", function( event ) {
var type = $( this ).attr( "type" );
if ( /date|email|month|number|search|tel|text|time|url|week/.test ( type )
&& event.keyCode == 13 ) {
showAllErrorMessages();
}
});
};
$( "form" ).each( createAllErrors );
</script>
You can customize the validation message position by adding this CSS code.
.form-control[required] {
margin-top: 40px !important;
margin-left: 100px !important;
}

I have a Special Idea about an Edit function

All the Functions below are under a $(document).ready(function()) !
First I have an input which you can fade in/out its looks like this:
<form>
<label for="vorname"> Vorname: </label> <input type="text" id="vorname"/></br>
<label for="nachname"> Nachname: </label> <input type="text" id="nachname"/></br>
<label for="alter">Alter:</label> <input type="number" Id="alter"/></br>
<label for="gender">Geschlecht:</label>
<select id="geschlecht">
<option id="Male">männlich</option>
<option id="Female">weiblich</option>
</select>
<input type="button" value="Zurückklappen" id="back"> //fadeOut
<input type="button" value="Absenden" class="send"/> //eventhandler
</form>
Then I have a click handler to make list entries
$('.send').click(function onClick(){
var age = $('#alter').val();
var preName = $('#vorname').val();
var secName = $('#nachname').val();
var gender = $('#geschlecht').val();
list.push ({
alter: age,
vorname: preName,
nachname: secName,
geschlecht: gender,
});
generateList();
stat();
save();
});
But I want an Edit function who takes the selected list entry,
$("#liste").click(function selectList (event) {
var target = $( event.target );
if ( target.is( "li" ) ) {
target.toggleClass('selected');
}
});
To take exactly this ONE (because i cant edit two at once, or can I? Would also be cool) selected Entry to edit it.
THIS is where i need help (the things before are only explanation, finished work there).
$(".edit").click(function (){
var index = $('.selected')
//this where the magic i think should
// happen somehow i must get an Index form the selcted list entry
function edit(index) {
// here fadeIN the form which is shown above.
$( "#block" ).fadeIn(500);
$( "#block" ).animate({width: '54.4%', opacity: '0.8',fontSize: '1.5em'}, 750);
$( "#block" ).animate({height: '40%', opacity: '0.8', fontSize: '3em'}, 750);
//this is my Idea:
//I want to call the already exsiting click function with an Index
//inside the edit function.
//so the function conitnues like this:
$('.send').click(function onClick(index){
var age = $('#alter').val(index);
var preName = $('#vorname').val(index);
var secName = $('#nachname').val(index);
var gender = $('#geschlecht').val(index);
liste[index].push = {
vorname: preName,
nachname: secName,
alter: age,
geschlecht: gender
};
generateList();
save();
});
}
});
I can post the whole Program if requested. it could be that ( or { are missing in this much of a code, but i asusuure you in my Program is everything right.
at the moment it looks like this:
$("#liste").click(function selectList (event) {
var target = $( event.target );
if ( target.is( "li" ) && !$("li").hasClass('selected')) {
target.addClass('selected');
}
else if (target.is( "li" ) && $("li").hasClass('selected')) {
target.removeClass('selected');
}
});
$('.deleteSel').click(function delSelectedEntries () {
alert("Ausgewählte Beiträge wuden gelöscht");
var sel = $('.selected'); //stores the entrys
sel.remove(); // removes only the list entrys temporaly
});
$(".edit").click(function editSelectedEntries(){
var index = $('.selected').attr("index");
edit(index);
});
edit Function:
function edit (index){
$( "#block" ).fadeIn(500);
$( "#block" ).animate({width: '54.4%', opacity: '0.8',fontSize: '1.5em'}, 750);
$( "#block" ).animate({height: '40%', opacity: '0.8', fontSize: '3em'}, 750);
$('#alter').val(list[index].alter);
$('#vorname').val(list[index].vorname);
$('#nachname').val(list[index].nachname);
$('#geschlecht').val(list[index].geschlecht);
$('.send').click(function onClick(){
var age = $('#alter').val();
var preName = $('#vorname').val();
var secName = $('#nachname').val();
var gender = $('#geschlecht').val();
list[index] = {
vorname: preName,
nachname: secName,
alter: age,
geschlecht: gender
};
generateList();
});

Mask and unmask input text in html

I have few text fields like SSN , phone number and email id. I would like to do something like onfocus it should display the whole content of that input box and on blur it should mask the content back to something (say asterix).Thanks in advance
You could switch the type of the <input> element between password and text in both events. See this example fiddle.
HTML
<input type="password" id="target" />
JS
<script>
var inp = document.querySelector( '#target' );
inp.addEventListener( 'focus', function(){
inp.type = 'text';
});
inp.addEventListener( 'blur', function(){
inp.type = 'password';
});
</script>
Try it like this:
<input type="text" id="emailId" name="emailId" />
Then, do a:
var emailIdValue = "";
$( document ).ready( function() {
emailIdValue = $( '#emailId' ).val();
$( '#emailId' ).val( "********" );
$( '#emailId' ).focus( function() {
$( this ).val( emailIdValue );
} ).focusout( function() {
emailIdValue = $( this ).val();
$( this ).val( '********' );
} );
} );
You could simply use <input type="password" /> if you want to do it simple.

Categories