I have made a custom jquery dropdown plugin which is seems to be working good on desktop and mobile.
However,on mobile we are using native html behavior and in desktop we are designing the dropdown as we need with the help of ul li and then appending it to the select tag.
But i am not able to make any selection from keyboard which we normally can from the default native dropdown. Is there any solution ?
could someone help me how should i do it with keyCode or is there any solution ?
alphaDropdown: function(){
(function(jQuery){
jQuery.fn.AlphaDropdown = function( configurations ){
var defaultConfigurations = {
disabledFirst: false
};
var extendedconfigurations = jQuery.extend(defaultConfigurations, configurations || {});
function setBackData( ){
jQuery('.selectr-desktop-custom').each(function(){
var selectedValue = jQuery(this).removeClass('active').find('select').eq(0).val();
var selectedIndex = jQuery(this).removeClass('active').find('select').eq(0)[0].selectedIndex;
if( !selectedValue || selectedValue == ""){
var dropdown = jQuery(this).find('select').eq(0)[0];
var _index = dropdown.selectedIndex;
if( _index >= 0 ){
selectedValue = dropdown.options[_index].innerText;
selectedIndex = _index;
}
}
if ( selectedIndex != -1 ) {
var moveBy = -(selectedIndex * 40), movewithY = 'translateY('+moveBy+'px)';
jQuery(this).find('ul').eq(0).css({
transform: movewithY
});
};
});
}
jQuery(this).each(function(){
if( jQuery(this).parents('.selectr-desktop-custom').length > 0 ){
jQuery(this).parents('.selectr-desktop-custom').children('ul').remove();
jQuery(this).unwrap('.selectr-desktop-custom');
}
var preselectedvalue = jQuery(this).val() ;
if( !preselectedvalue || preselectedvalue == ""){
var dropdown = jQuery(this).eq(0)[0];
var _index = dropdown.selectedIndex;
if( _index >= 0 ){
preselectedvalue = dropdown.options[_index].innerText;
}
}
var list = "<ul>"
jQuery(this).wrap("<div class='selectr-desktop-custom' tabindex='0'></div>");
jQuery(this).find('option').each(function(){
var currentValue = jQuery(this).val() && jQuery(this).val().trim() != ""?jQuery(this).val():jQuery(this).text();
if( jQuery(this).index() == 0 ){
if( extendedconfigurations.disabledFirst && currentValue == preselectedvalue ){
list += "<li class='disabled active drop' alpha-value='" + currentValue +"'>" + jQuery(this).text() + "</li>";
}else if( extendedconfigurations.disabledFirst && currentValue != preselectedvalue ){
list += "<li class='disabled drop' alpha-value='" + currentValue+"'>" + jQuery(this).text() + "</li>";
}else if( !extendedconfigurations.disabledFirst && currentValue == preselectedvalue ){
list += "<li class='active' alpha-value='" + currentValue +"'>" + jQuery(this).text() + "</li>";
}
else{
list += "<li alpha-value='" + currentValue +"'>" + jQuery(this).text() + "</li>";
}
}
else{
if( currentValue == preselectedvalue ){
list += "<li class='active' alpha-value='"+ currentValue +"'>"+ jQuery(this).text() +"</li>";
}else{
list += "<li alpha-value='"+ currentValue +"'>"+ jQuery(this).text() +"</li>";
}
}
});
list += "</ul>";
jQuery(this).before(list);
jQuery(this).parents('.selectr-desktop-custom').click(function(e){
e.stopPropagation();
jQuery('.selectr-desktop-custom').removeClass('active');
jQuery(this).addClass('active');
jQuery(this).find('ul').eq(0).css('transform','translateY(0)');
}).find('ul').eq(0).find('li').click(function(e){
var _index = jQuery(this).index();
var moveBy = -(_index * 40), movewithY = 'translateY('+moveBy+'px)';
var ul = jQuery(this).parent();
var dropdown = ul.parent().find('select').eq(0);
jQuery(this).parent().css({
transform: movewithY
});
var seletedValue = jQuery(this).attr('alpha-value') || null;
if( seletedValue ){
dropdown.val(seletedValue).find('option').each(function(){
if( jQuery(this).text() === seletedValue || jQuery(this).val() === seletedValue ){
jQuery(this).attr('selected','selected');
}else{
jQuery(this).attr('selected',null);
}
});
dropdown[0].selectedIndex = _index;
dropdown.trigger('change');
}
jQuery(this).addClass('active').siblings().removeClass('active').closest('.selectr-desktop-custom').removeClass('active');
e.stopPropagation();
e.stopImmediatePropagation();
return false;
});
jQuery('body').click(function(e){
setBackData();
});
});
setBackData();
return this;
}
})($);
}
Related
i want to insert following Java Script into my Wordpress plugin
please help me
this what i written which validate from Sheetsu API
Details at - https://codepen.io/santosh-panda/pen/YOedWv?editors=1010
<input id="input-text_flacement-id">
<script src="https://script.sheetsu.com/"></script>
<script>
var input = document.getElementById('input-text_flacement-id');
var is_focused = false;
input.onfocus = function () {
is_focused = true;
}
input.onblur = function () {
if (is_focused) {
is_focused = false;
check_id(input.value);
}
}
function check_id(id) {
if (id.match(/\d{4}-\d{4}-\d{4}/)) {
document.body.append("\nchecking...");
function successFunc(data) {
var row = data.filter((row)=>row['adhar_no'] == id)
if(row.length){
document.body.append("\nid found");
}
else{
document.body.append('\nid not found');
}
}
// Get all rows where column 'adhar_no' is '3894-8873-7149'
var searchQuery = {
status: 'active',
};
Sheetsu.read("https://sheetsu.com/apis/v1.0dh/dd98887de543/", {
search: searchQuery
}, successFunc);
}
else {
document.body.append('\ninvalid id');
}
}
</script>
this code ^^ want to inster in Wordpress plugin JS
which excutive in http://www.flacement.com/jobssearch/iffco-tokio-job-in-jharsuguda/
i want it when some one apply [apply text field 1
in flacement ID it should validate from JS API if found then procedd or if not then invalide as first code. code is ready but i am confuse where to instert in follwing so it start working
Number.prototype.clamp = function(min, max) {
return Math.min(Math.max(this, min), max);
};
(function($){
$.fn.filterFind = function(selector) {
return this.find('*') // Take the current selection and find all descendants,
.addBack() // add the original selection back to the set
.filter(selector); // and filter by the selector.
};
$.fn.svgDraw = function(progress) {
this.filterFind('path').each(function() {
var pathLength = this.getTotalLength();
$(this).css('strokeDasharray', pathLength + ' ' + pathLength);
$(this).css('strokeDashoffset', pathLength * ((1 - progress)).clamp(0, 1));
});
return this;
};
$(document).ready(function(){
if( $('.jobs-modal').length ){
setTimeout(function(){
$('.jobs-modal').removeClass('hide');
}, 500);
$('.jp-apply-button').click(function(e){
e.preventDefault();
$('body').addClass('jobs-modal-open');
$('.jobs-modal').addClass('open');
});
$('.jobs-modal .modal-close').click(function(e){
e.preventDefault();
$(this).parents('.jobs-modal').removeClass('open');
$('body').removeClass('jobs-modal-open');
});
$('.jobs-modal-content').each(function(k){
$(this).find( '.inputfile' ).each(function(k){
var label = this.nextElementSibling;
var labelVal = label.innerHTML;
$(this).change(function(e){
var fileName = '';
if( this.files && this.files.length > 2 )
fileName = ( this.getAttribute( 'data-multiple-caption' ) || '' ).replace( '{count}', this.files.length );
else
fileName = e.target.value.split( '\\' ).pop();
if( fileName ){
label.querySelector( 'span' ).innerHTML = fileName;
var num = $(this).parents('.modal-input-fileinput').attr('data-files');
num = Number(num) + 1;
$(this).parents('.modal-input-fileinput').attr('data-files', num);
}else{
label.innerHTML = labelVal;
}
});
$(this).focus(function(){ $(this).addClass('has-focus') });
$(this).blur(function(){ $(this).removeClass('has-focus') });
});
});
if( $('.choose_file_multi_add').length ){
var i = 1;
$('.choose_file_multi_add').click(function(e){
e.preventDefault();
var key_id = $(this).data('key');
var parent = $(this).parents('.modal-input-fileinput');
var input = $('#file-input-tpl-'+key_id).html();
var label = $('#file-label-tpl-'+key_id).html();
var id = key_id + '-'+i;
var key = key_id + '-key-'+i;
input = input.replace( '{id}', id ).replace( '{id}', id ).replace( '{id}', id );
input = input.replace( '{nr}', i ).replace( '{nr}', i ).replace( '{nr}', i );
input = input.replace( '{key}', key ).replace( '{key}', key ).replace( '{key}', key );
label = label.replace( '{id}', id ).replace( '{id}', id ).replace( '{id}', id );
$(input).insertBefore( $('#'+key_id+' .choose_file_multi_add') );
$(label).insertBefore( $('#'+key_id+' .choose_file_multi_add') );
//parent.prepend( input );
//parent.prepend( label );
$('#'+id).change(function(e){
var fileName = '';
if( this.files && this.files.length > 1 )
fileName = ( this.getAttribute( 'data-multiple-caption' ) || '' ).replace( '{count}', this.files.length );
else
fileName = e.target.value.split( '\\' ).pop();
if( fileName ){
$('#label-'+id).find('span.name').text( fileName );
var num = $(this).parents('.modal-input-fileinput').attr('data-files');
num = Number(num) + 1;
$(this).parents('.modal-input-fileinput').attr('data-files', num);
}
});
$('.choose_file_multi .remove').click(function(e){
e.preventDefault();
var id = $(this).parents('.choose_file_multi').attr('id');
id = id.replace('label-', 'jobgroup-');
var num = $(this).parents('.modal-input-fileinput').attr('data-files');
num = Number(num) - 1;
$(this).parents('.modal-input-fileinput').attr('data-files', num);
$('.'+id).remove();
recalculateInputs();
return false;
});
$('#'+id).click();
recalculateInputs();
i++;
});
}
function recalculateInputs(){
if( $('.modal-input-fileinput.multiple .modal-input-multifile').length == 0 ){
$('.disabled-file-placeholder').addClass('input-reqired');
}else{
$('.disabled-file-placeholder').removeClass('input-reqired');
}
}
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
var sending_form = false;
$('.progress-button .progress-circle').svgDraw(0);
$("form#jobs-modal-form").submit(function(e){
e.preventDefault();
var self = this;
var toreturn = true;
$('#jobs-modal-form .input-reqired').each(function(){
var value = $(this).val();
var is_checked = false;
if( $(this).hasClass('input-job_email') ){
if( value == '' || !validateEmail(value) ){
$(this).addClass('alert').parents('.jobs-modal-input').addClass('alert');
toreturn = false;
}else{
$(this).removeClass('alert').parents('.jobs-modal-input').removeClass('alert');
}
}else if( $(this).hasClass('modal-input-checkbox') ){
var checkboxes_checked = 0;
$(this).parents('.checkbox_field').find('input[type="checkbox"]').each(function(){
var checked = $(this).prop('checked');
if( checked == true ){
checkboxes_checked++;
}
});
if( checkboxes_checked == 0 ){
$(this).addClass('alert').parents('.jobs-modal-input').addClass('alert');
toreturn = false;
}else{
$(this).removeClass('alert').parents('.jobs-modal-input').removeClass('alert');
}
}else if( $(this).hasClass('modal-input-radio') ){
var checkboxes_checked = 0;
$(this).parents('.radio_field').find('input[type="radio"]').each(function(){
var checked = $(this).prop('checked');
if( checked == true ){
checkboxes_checked++;
}
});
if( checkboxes_checked == 0 ){
$(this).addClass('alert').parents('.jobs-modal-input').addClass('alert');
toreturn = false;
}else{
$(this).removeClass('alert').parents('.jobs-modal-input').removeClass('alert');
}
}else{
if( value == '' ){
$(this).addClass('alert').parents('.jobs-modal-input').addClass('alert');
toreturn = false;
}else{
$(this).removeClass('alert').parents('.jobs-modal-input').removeClass('alert');
}
}
});
var input = document.getElementById('input-text_flacement-id');
var is_focused = false;
input.onfocus = function () {
is_focused = true;
}
input.onblur = function () {
if (is_focused) {
is_focused = false;
check_id(input.value);
}
}
function check_id(id) {
if (id.match(/\d{4}-\d{4}-\d{4}/)) {
document.body.append("\n checking...");
function successFunc(data) {
var row = data.filter((row)=>row['adhar_no'] == id)
if(row.length){
document.body.append("\n id found");
}
else{
document.body.append('\n id not found');
}
}
// Get all rows where column 'adhar_no' is '3894-8873-7149'
var searchQuery = {
status: 'active',
};
Sheetsu.read("https://sheetsu.com/apis/v1.0dh/dd98887de543/", {
search: searchQuery
}, successFunc);
} else {
document.body.append('\n invalid id');
}
}
if( toreturn && sending_form == false ){
/*
var progressBTN = $(self).find('.progress-button');
progressBTN.addClass('loading');
var progressCRCL = $(self).find('.progress-circle');
var progress = 0;
var intervalId = setInterval(function() {
progress += Math.random() * 0.5;
progressCRCL.svgDraw(progress);
if(progress >= 1) {
clearInterval(intervalId);
}
}, 200);
*/
sending_form = true;
$('.job-submit').hide();
$('.jobs-sending').show();
var formData = new FormData($("form#jobs-modal-form")[0]);
$.ajax({
type: 'POST',
url: jpsd.ajaxurl,
data: formData,
processData: false,
contentType: false,
success: function (data) {
//clearInterval(intervalId);
//progressCRCL.svgDraw(1);
// Clear all smaces and newlines that can happen on response on some servers
data = data.replace(/\s/g, "");
if( data == 'ok' ){
//setTimeout(function(){
// $(self).find('.progress-button').addClass('success');
//}, 500);
//setTimeout(function(){
$(self).slideUp();
$('#job-apply-confirmation').slideDown();
//}, 1000);
}else{
//setTimeout(function(){
// $(self).find('.progress-button').addClass('error');
//}, 500);
//setTimeout(function(){
$('.jobs-sending').hide();
//}, 1000);
}
return false;
},
});
return false;
}
return false;
});
/*
$('.progress-button').on('click', function() {
var $button = $(this);
$(this).addClass('loading');
var $progress = $(this).find('.progress-circle');
var progress = 0;
var intervalId = setInterval(function() {
progress += Math.random() * 0.5;
$progress.svgDraw(progress);
if(progress >= 1) {
clearInterval(intervalId);
//console.log("cleared interval");
$button.removeClass('loading');
if($button.attr('data-result') == "true") {
$button.addClass('success');
}
else {
$button.addClass('error');
}
}
}, 300);
// Now that we finished, unbind
$(this).off('click');
});
*/
} // end .jobs-modal length
});
})(jQuery);
I am using Opencart v2.2.0. Search box is autocomplete and that part is alright. But now I need to make letters bold as I type in the search box.
Example:
The user starts typing "some", and as he types, the results are:
something
awesome
etc.
NOTICE: The words "something" and "awesome" are just an example, in real time I do not know what search terms would user type in.
So far I have this code, but as I am not really a js/jquery expert, I need help implementing the upper request. Thank you all.
//<![CDATA[
function doLiveSearch( ev, keywords ) {
if( ev.keyCode == 38 || ev.keyCode == 40 ) {
return false;
}
$('#autosearch_search_results').remove();
updown = -1;
if( keywords == '' || keywords.length < 2 ) {
return false;
}
keywords = encodeURI(keywords);
$.ajax({url: $('base').attr('href') + 'index.php?route=module/autosearch/ajax_asr&keyword=' + keywords, dataType: 'json', success: function(result) {
if( result.length > 0 ) {
var eList = document.createElement('ul');
eList.id = 'autosearch_search_results';
var eListElem;
var eLink;
var eImage;
for( var i in result ) {
eListElem = document.createElement('li');
eLink = document.createElement('a');
if( (result[i].thumb) != '' )
{
eImage = document.createElement('img');
eImage.src = result[i].thumb;
eLink.appendChild(eImage);
}
// name
var el_span = document.createElement('name');
var textNode = document.createTextNode(result[i].name);
eLink.appendChild(el_span);
el_span.appendChild(textNode);
// model
if( (result[i].model) != '' )
{
var el_span = document.createElement('model');
var textNode = document.createTextNode(result[i].model);
eLink.appendChild(el_span);
el_span.appendChild(textNode);
}
if( typeof(result[i].href) != 'undefined' ) {
eLink.href = result[i].href;
}
else {
eLink.href = $('base').attr('href') + 'index.php?route=product/product&product_id=' + result[i].product_id + '&keyword=' + keywords;
}
eListElem.appendChild(eLink);
if( (result[i].price) != '' )
{
var br = document.createElement("br");
eLink.appendChild(br);
// special price
if( (result[i].special) != '' )
{
var el_span = document.createElement('special-price');
var textNode = document.createTextNode(result[i].special);
eLink.appendChild(el_span);
el_span.appendChild(textNode);
}
// price
var el_span = document.createElement('price');
var textNode = document.createTextNode(result[i].price);
eLink.appendChild(el_span);
el_span.appendChild(textNode);
}
// quantity/stock
if( (result[i].stock) != '' )
{
var br = document.createElement("br");
eLink.appendChild(br);
eLink.appendChild( document.createTextNode(result[i].stock) );
}
eList.appendChild(eListElem);
}
if( $('#autosearch_search_results').length > 0 ) {
$('#autosearch_search_results').remove();
}
//view all results
if( (result[i].viewall) != '' )
{
eListElem = document.createElement('li');
eLink = document.createElement('a');
var el_span = document.createElement('viewall');
var textNode = document.createTextNode(result[i].viewall);
eLink.appendChild(el_span);
el_span.appendChild(textNode);
eLink.href = $('base').attr('href') + 'index.php?route=product/search&search=' + keywords;
eListElem.appendChild(eLink);
eList.appendChild(eListElem);
}
$('#search').append(eList);
}
}});
return true;
}
function upDownEvent( ev ) {
var elem = document.getElementById('autosearch_search_results');
var fkey = $('#search').find('[name=search]').first();
if( elem ) {
var length = elem.childNodes.length - 1;
if( updown != -1 && typeof(elem.childNodes[updown]) != 'undefined' ) {
$(elem.childNodes[updown]).removeClass('highlighted');
}
// Up
if( ev.keyCode == 38 ) {
updown = ( updown > 0 ) ? --updown : updown;
}
else if( ev.keyCode == 40 ) {
updown = ( updown < length ) ? ++updown : updown;
}
if( updown >= 0 && updown <= length ) {
$(elem.childNodes[updown]).addClass('highlighted');
var text = elem.childNodes[updown].childNodes[0].text;
if( typeof(text) == 'undefined' ) {
text = elem.childNodes[updown].childNodes[0].innerText;
}
}
}
return false;
}
var updown = -1;
$(document).ready(function(){
$('#search').find('[name=search]').attr('autocomplete', 'off'); //disable autocomplete
$('#search').find('[name=search]').first().keyup(function(ev){
doLiveSearch(ev, this.value);
}).focus(function(ev){
doLiveSearch(ev, this.value);
}).keydown(function(ev){
upDownEvent( ev );
}).blur(function(){
window.setTimeout("$('#autosearch_search_results').remove();updown=0;", 1500);
});
$(document).bind('keydown', function(ev) {
try {
if( ev.keyCode == 13 && $('.highlighted').length > 0 ) {
document.location.href = $('.highlighted').find('a').first().attr('href');
}
}
catch(e) {}
});
});
//]]>
just add a function that highlights all the searched text end run it on every text you add to your html:
function highlightQuery(string,searchQuery){
if(!string){
return "";
}
var expr = searchQuery;
expr = expr.replace(/\s+/, "|",searchQuery);
var regex = new RegExp(expr,"gi");
return string.replace(regex, function($1){
return '<span class="highlight">'+ $1 +'</span>';
});
}
We are trying to do the formatting part at javascript
so that only display should be done at HTML part
Execute the below function on typeahead ,and then you just need to display
the resultant array( formattedResult ) in HTML.
formattedResult will contain the formatted text.
While displaying formattedResult array in HTML , put 2nd position text
in bold of each iterated item.
Please try following code:-
//argument types searchList(Array) and searchWord(String)
function formatResult(searchList, searchWord ){
var formattedResult = [[]];
for(var prop in searchList){
if(searchList[prop].indexOf("some")!=-1)
{
var index= searchList[prop].indexOf(searchWord );
var temp = [];
temp.push(searchList[prop].substring(0,index));
temp.push(searchWord.toUpperCase());
temp.push(searchList[prop].substring(index + searchWord.length,
searchList[prop].length));
//console.log(temp);
formattedResult.push(temp);
}
else{
formattedResult.push(searchList[prop])
}
}
return formattedResult;
}
I have text area controls in my page and I had code it such way that when user click on text area or hit 'ENTER' key that time it will create bullet-list in text area. But problem is that if user click on text area and it will create bullet-list but if user does not type anything in text area then it should get empty and bullet should be removed. In simple way text area bullet-list should get removed if it has no data in it.
And one more thing is to prevent user deleting bullet from text area.
here is my code :
<textarea name="MondayAcomp" id="MondayAcomp" cols="45" rows="5" onKeyDown="if(event.keyCode == 13) return false;" onKeyUp="bulletOnEnter(this.id)" onFocus="onfoc(this.id)" onBlur="onFocOff(this.id)" style="margin: 0px; width: 200px; height: 219px;"></textarea>
Javascript functions:
function onfoc(id) {
if (document.getElementById(id).value == "") {
document.getElementById(id).value += '• ';
}
}
function onFocOff(id) {
if (document.getElementById(id).value == '• ') {
document.getElementById(id).empty;
}
}
function bulletOnEnter(id) {
var keycode = (event.keyCode ? event.keyCode : event.which);
if (keycode == '13') {
event.preventDefault();
document.getElementById(id).value += '\n• ';
}
var txtval = document.getElementById(id).value;
if (txtval.substr(txtval.length - 1) == '\n') {
document.getElementById(id).value = txtval.substring(0, txtval.length - 1);
}
}
jsfiddle here
It is not .empty, it is .value = "";.
For the keyCode you need to pass event parameter to your callback function too.
You can prevent adding empty lines, by checking the last line in your return key callback too.
Only way I can imageine, to prevent deleting the bullets, is a loop at the end and check each line start.
function onfoc(id) {
if( document.getElementById(id).value == '' ) {
document.getElementById(id).value +='• ';
}
}
function onFocOff(id) {
if( document.getElementById(id).value == '• ' ) {
document.getElementById(id).value = '';
}
}
function bulletOnEnter(event, id) {
event = event || window.event;
// handle 'return' key
var keycode = event.keyCode || event.charCode || event.which;
var txtval = document.getElementById(id).value;
if( keycode == 13 && txtval.substr(txtval.length - 2) != '• ' ) {
event.preventDefault();
document.getElementById(id).value += '\n• ';
}
// remove possible last empty line
txtval = document.getElementById(id).value;
if( txtval.substr(txtval.length - 1) == '\n' ) {
document.getElementById(id).value = txtval.substring(0, txtval.length - 1);
}
// check if each line starts with a bullet
var lines = document.getElementById(id).value.split('\n')
for( var i = 0, l = lines.length; i < l; i++ ) {
if( lines[i].substr(0, 1) !== '•' ) {
lines[i] = '•' + lines[i];
}
}
document.getElementById(id).value = lines.join('\n');
}
<textarea id="MondayAcomp" onKeyDown="if(event.keyCode == 13) return false;" onKeyUp="bulletOnEnter(event, this.id)" onFocus="onfoc(this.id)" onBlur="onFocOff(this.id)"></textarea>
As additional answer, I converted the code to use jQuery instead of plain JS, because you tagged your question with jQuery.
$('#MondayAcomp').on({
focus: function() {
if( $(this).val() == '' ) {
$(this).val($(this).val() + '• ');
}
},
blur: function() {
if( $(this).val() == '• ' ) {
$(this).val('');
}
},
keydown: function(e) {
if( e.keyCode == 13 ) {
e.preventDefault();
}
},
keyup: function(e) {
var element = $(this),
value = element.val();
// handle 'return' key
if( e.keyCode == 13 && value.substr(-2) != '• ' ) {
e.preventDefault();
element.val((value += '\n• '));
}
// remove possible last empty line
if( value.substr(-1) == '\n' ) {
element.val((value = value.substring(0, value.length - 1)));
}
// check if each line starts with a bullet
var lines = element.val().split('\n')
for( var i = 0, l = lines.length; i < l; i++ ) {
if( lines[i].substr(0, 1) !== '•' ) {
lines[i] = '•' + lines[i];
}
}
element.val(lines.join('\n'));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="MondayAcomp"></textarea>
Working with an existing script that checks input values on form submission against existence of minimum quantity. I need to include a condition to check for the existence of maximum quantity and display an error message when the condition is not met. I believe it's a matter of editing the existing conditional logic but for the life of me I cannot get the edits to function without hosing up the functioning minimum condition. Rather than submitting my failed attempt at altering the code I'm submitting a functional version that only validates minimum quantities.
$('#button-cart').on('click', function() {
var total_quantity = 0;
var min_oneside = parseInt("<?php echo $min_oneside; ?>");
var min_bothside = parseInt("<?php echo $min_bothside; ?>");
var min_noprint = parseInt("<?php echo $min_noprint; ?>");
var min_standard = parseInt(" <?php echo $minimum; ?>");
var max_standard = parseInt(" <?php echo $maximum; ?>");
var validQty = true;
var validMaxQty = true;
var validInput = true;
var oth_minimum = "Quantity must be at least <?php echo $minimum; ?>";
var oth_maximum = "Quantity must be less than <?php echo $maximum; ?>"
$('#content').find('input[name^="option-quantity"]').each(function(){
total_quantity = total_quantity + parseInt($(this).val());
});
$('#content').find('input[name="quantity"]').each(function(){
total_quantity = total_quantity + parseInt($(this).val());
});
var element = $("label:contains('Printing')").attr('for');
if(element === undefined){
if( total_quantity < min_standard ) {
validQty = false;
validInput = false;
oth_minimum = "Quantity must be at least " + min_standard;
}else if (total_quantity > max_standard){
validQty = false;
validInput = false;
oth_message = oth_maximum;
}
} else {
if ( ($("#" + element + " option:selected").text()).match("Printed One Side") ){
if( total_quantity < min_oneside ) {
validQty = false;
validInput = false;
oth_minimum = "Quantity must be at least " + min_oneside;
}else if (total_quantity > max_standard){
validQty = false;
validInput = false;
oth_message = oth_maximum;
}
}
if ( ($("#" + element + " option:selected").text()).match("Printed Both Sides") ){
if( total_quantity < min_bothside ) {
validQty = false;
validInput = false;
oth_minimum = "Quantity must be at least " + min_bothside;
}else if (total_quantity > max_standard){
validQty = false;
validInput = false;
oth_message = oth_maximum;
}
}
if ( ($("#" + element + " option:selected").text()).match("No Printing") ){
if( total_quantity < min_noprint ) {
validQty = false;
validInput = false;
oth_minimum = "Quantity must be at least " + min_noprint;
}else if (total_quantity > max_standard){
validQty = false;
validInput = false;
oth_message = oth_maximum;
}
}
}
if(!validQty) {
$('#errorQuantity').html(oth_minimum);
}
var minimum = "Quantity must be at least <?php echo $minimum; ?>";
if($('#errorQuantity').length > 0 && validQty) {
var quantity = 0;
$('#errorQuantity').empty();
$('input[type=number]').each(function () {
var currentId = $(this).attr('id');
checkboxId = currentId.replace("quantity-", "");
if(isNaN($(this).val()) || $(this).val() < 0) {
$(this).focus();
$(this).css('background-color', 'red');
validInput = false;
} else {
quantity += parseInt($(this).val());
}
});
if(quantity <= 0) {
$('#errorQuantity').append(minimum);
validInput = false;
}
}
if(validInput){
$('input[type=number]').each(function () {
$(this).css('background-color', '#FFFFFF');
});
$('#errorQuantity').empty();
$.ajax({
url: 'index.php?route=checkout/cart/add',
type: 'post',
data: $('.product-info input[type=\'text\'], .product-info input[type=\'number\'], .product-info input[type=\'date\'], .product-info input[type=\'datetime\'], .product-info input[type=\'hidden\'], .product-info input[type=\'radio\']:checked, .product-info input[type=\'checkbox\']:checked, .product-info select, .product-info textarea'),
dataType: 'json',
beforeSend: function() {
$('#button-cart').attr('disabled', true);
$('#button-cart').after('<i class="fa fa-circle-o-notch fa-spin"></i>');
},
success: function(json) {
$('.alert, .text-danger').remove();
$('.form-group').removeClass('has-error');
$('#button-cart').next('.fa-spin').remove();
$('#button-cart').attr('disabled', false);
if (json['error']) {
var errors = '';
if (json['error']['option']) {
for (i in json['error']['option']) {
var element = $('#input-option' + i.replace('_', '-'));
element.parents('.form-group').first().find('> label + div').append('<div class="text-danger">' + json['error']['option'][i] + '</div>');
}
}
if (json['error']['recurring']) {
$('select[name="recurring_id"]').after('<span class="error">' + json['error']['recurring'] + '</span>');
}
// Highlight any found errors
$('.text-danger').each(function() {
$(this).parents('.form-group').first().addClass('has-error');
});
}
if (json['success']) {
$('.tb_widget_cart > .tb_nav').load('index.php?route=common/cart/info .tb_nav > *');
window.location = $('base').attr('href') + 'index.php?route=checkout/cart';
//displayNotice('product', 'success', 'product', json['success']);
}
}
});
}
});
Should be something like :
if(element === undefined){
if( total_quantity < min_standard ) {
validQty = false;
validInput = false;
oth_message = oth_minimum;
}else if (total_quantity > max_standard){
validQty = false;
validInput = false;
oth_message = oth_maximum;
}
} else {
if ( ($("#" + element + " option:selected").text()).match("Printed One Side") ){
if( total_quantity < min_oneside ) {
validQty = false;
validInput = false;
oth_message = "Quantity must be at least " + min_oneside;
}
}
if ( ($("#" + element + " option:selected").text()).match("Printed Both Sides") ){
if( total_quantity < min_bothside ) {
validQty = false;
validInput = false;
oth_message = "Quantity must be at least " + min_bothside;
}
}
if ( ($("#" + element + " option:selected").text()).match("No Printing") ){
if( total_quantity < min_noprint ) {
validQty = false;
validInput = false;
oth_message = "Quantity must be at least " + min_noprint;
}
}
}
if(!validQty) {
$('#errorQuantity').html(oth_message);
}
You can add in the same way for the other conditionals, I added only for the first one.
I was wondering wether it was possible to know exactly where in the dom the text that is selected is?
I am currently using the following function to know what text is being selected, but I want to be able to return its position as well
Selector = {};
Selector.getSelected = function(){
var t = '';
if(window.getSelection){
t = window.getSelection();
}else if(document.getSelection){
t = document.getSelection();
}else if(document.selection){
t = document.selection.createRange().text;
}
return t;
}
and I can also find what the parent element is with the following:
function getSelectionStart(){
var node = document.getSelection().anchorNode;
var startNode = (node.nodeName == "#text" ? node.parentNode : node);
return startNode;
}
but is there a way for me to know with js what the character position it has depending on where I click?
I ended up dynamically addressing each character as a seperate span tag and it's index.
This is what is currently doing what I want.
$('#codeinput ul' || '#selectednote li .char').click( function() {
if ($('#selectednote li *').size() < 2)
{
$('#codeinput h1').animate({opacity: '0.6'}, 200);
inputtype = 1;
inputnode = '#codeinput #selectednote li'
console.log('focus is shifted to ' + inputnode)
$('#codeinput #selectednote li').animate({opacity: '0.9'}, 200);
}
else
{
$('#selectednote li .char').click(function() {
k = 0
$('#codeinput h1').animate({opacity: '0.6'}, 200);
var char = $(this).attr('id')
inputnode = char
$('#caret').insertAfter('#selectednote li span:eq(' + (parseInt(inputnode) + parseInt(k)) + ')');
inputtype = 2;
console.log('clicked on ' + inputnode)
$('#codeinput #selectednote li').animate({opacity: '0.9'}, 200);
});
};
});
function sendinputtodom(input,type) {
$(".char").each(function(){ $(this).attr('id', $(this).index())});
if (inputtype == 2) {
var from = '#selectednote li span:eq(' + (parseInt(inputnode) + parseInt(k)) + ')';
console.log(from)
$('<span class="char">' + input + '</span>').insertAfter(from);
k = k + 1;
$('#caret').insertAfter('#selectednote li span:eq(' + (parseInt(inputnode) + parseInt(k)) + ')');
if($('#afterinput').size() < 1)
{
}
}
else
{
$('<span class="char">' + input + '</span>').appendTo(inputnode);
}
$(".char").each(function(){ $(this).attr('id', $(this).index())});
};
It isn't elegant, clean or light but it gets the job done.