HTML Input (Javascript) [closed] - javascript

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
please help me
I have a script which works on First Page Load, And when i use the function of this script again is doesn't work until i refresh the page, Means i want this script to work always, Not only when i will refresh the page, here is the script:
$(function(){
var fullEmail = $('#email').val();
console.log(fullEmail.length);
if(fullEmail.length>15)
{
textDot = fullEmail.substr(0, 14)+'...';
$('#email').val(textDot);
}
var oldText = $('#email').val();
$('#email').bind({
mouseover : function () {
$('#email').val(fullEmail);
},
mouseout: function () {
$('#email').val(oldText);
}
});
});
thanks in advance..

I have created a JSFiddle to demonstrate this. When you type in the email and then leave the input box, it shortens. When you re-enter the input box it expands back to its full length...
$('#email').bind('change', function () {
$self = $(this);
var fullEmail = $self.val();
var shortEmail = fullEmail;
if(fullEmail.length > 15) {
shortEmail = fullEmail.substr(0, 14)+'...';
$self.val(shortEmail );
}
$self.bind({
focus: function () {
$self.val(fullEmail);
},
blur: function () {
$self.val(shortEmail);
}
});
});

var oldText;
var fullEmail;
function smt(){
fullEmail = $('#email').val();
console.log(fullEmail.length);
if(fullEmail.length>15)
{
textDot = fullEmail.substr(0, 14)+'...';
$('#email').val(textDot);
}
oldText = $('#email').val();
}
$(function(){
$('#email').bind({
mouseover : function () {
smt();
$('#email').val(fullEmail);
},
mouseout: function () {
smt();
$('#email').val(oldText);
}
});
});

Related

Is there any way I can dry out this file? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
Take a look at my files, the one thing that is bothering me for the moment is the repeated section and panel. I must not be able to see the bigger picture, so can anyone tell me a better and dryer method to code?
$(function() {
let pent = {
init : function () {
this.cacheDom();
this.bindEvents();
},
cacheDom: function () {
this.$el = $('#naver');
this.$button = this.$el.find('#xCancel');
this.$set = this.$el.find(".setting");
this.$section = [
this.$sectionA = this.$el.find('#set1'),
this.$sectionB = this.$el.find('#set2'),
this.$sectionC = this.$el.find('#set3'),
this.$sectionD = this.$el.find('#set4')
];
this.$panelA = this.$el.find('#settbox1');
this.$panelB = this.$el.find('#settbox2');
this.$panelC = this.$el.find('#settbox3');
this.$panelD = this.$el.find('#settbox4');
},
bindEvents: function () {
this.$button.on('click', this.hidePanel.bind(this));
this.$sectionA.on('click', this.showPanelA.bind(this));
this.$sectionB.on('click', this.showPanelB.bind(this));
this.$sectionC.on('click', this.showPanelC.bind(this));
this.$sectionD.on('click', this.showPanelD.bind(this));
},
showPanelA: function () {
this.$button.show();
this.$panelA.slideDown(100);
},
showPanelB: function () {
this.$button.show();
this.$panelB.slideDown(100);
},
showPanelC: function () {
this.$button.show();
this.$panelC.slideDown(100);
},
showPanelD: function () {
this.$button.show();
this.$panelD.slideDown(100);
},
hidePanel : function () {
this.$set.slideUp(100);
this.$button.hide();
},
};
pent.init();
});
Better code would be:
$('#xCancel').on('click', function() {
$('.setting').slideUp(100);
$(this).hide();
});
$('.set1').on('click', function() {
$('#xCancel').show();
$('.settbox').slideDown(100);
});
Just follow DRY principle and make things easier. I mean if you need to do the same operation for more elements, why you can't use class as universal selector?
On youtube are lots of tutorials or you can visit jQuery documentation website.

Can i shorten this jquery code [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I have around 20 buttons that view different type av boxes when clicked, so my JS code is really long. The function works perfect but im wondering if there is a way to shorten this code or make it more cleaner?
// Content lvl 1
function show(sel) {
var el = $(sel);
el.fadeToggle();
$('.showmore-1').not(el).fadeOut("slow");
}
$('.showmore-1').hide();
$('#click-1a').click(function () {
show('#showmore-1a');
});
$('#click-1b').click(function () {
show('#showmore-1b');
});
// Content lvl 2
function show(sel) {
var el = $(sel);
el.fadeToggle();
$('.showmore-2').not(el).fadeOut("slow");
}
$('.showmore-2').hide();
$('#click-2a').click(function () {
show('#showmore-2a');
});
$('#click-2b').click(function () {
show('#showmore-2b');
// Content lvl 3
function show(sel) {
var el = $(sel);
el.fadeToggle();
$('.showmore-3').not(el).fadeOut("slow");
}
$('.showmore-3').hide();
$('#click-3a').click(function () {
show('#showmore-3a');
});
$('#click-3b').click(function () {
show('#showmore-3b');
});
And this will continue to click 20 i maybe will do even more.
YES
$("[id^=click]").click(function (e) { //match elements with ID's starting with "click"
oldSelector = e.target.id; //get the ID of the clicked element
newSelector = oldSelector.replace("click", "showmore"); //replace string
show(newSelector);
});
Advantage is that the code keeps working if you add more or less buttons the same way. No need to update this code for it, nor the HTML itself.
Body as 1 liner:
$("[id^=click]").click(function (e) {
show(e.target.id.replace("click", "showmore"));
});
If your HTML is editable, try something like this:
<button class="clickable" data-for="#showmore-1">Click</button>
Then your jQuery becomes:
$(function() {
$(document.body).on("click",".clickable",function(e) {
e.preventDefault();
show(this.getAttribute("data-for"));
});
function show(sel) { ... }
});
If your elements are like:
<div id="click-1">click me</div>
make them like:
<div class="showing-trigger" data-target-id="showmore-1">click me</div>
and then your handlers could be:
$('.showing-trigger').on('click', function () {
show('#' + $(this).data('target-id'));
});
Note that with this code your triggers can show a div with any id.
for ( var counter = 0; counter < 20; counter++)
{
$('#click-' + counter).click(function () {
var idCounter = $( this ).attr( "id" ).split( "-" )[1];
show('#showmore-' + idCounter );
});
}
or better yet, bind a click event to a class rather than on id
Try this:
for(var i=1,l=21; i<l; i++){
(function(i){ // closure scopes off i so it's not at end of loop when Event occurs
$('#click-'+i).click(function(){
$('.showmore').fadeOut('slow', function(){ // fade showmore class out
$('#showmore-'+i).show(); // show just the one you want
});
});
})(i);
}
It can be shortened to this:
$("[id^= click]").click(function (e) {
oldSelector = e.target.id; //get the ID of the clicked element
newSelector = oldSelector.replace("click", "showmore");
show(newSelector);
});

Getting variable value out of jQuery [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Is there any way to extract value of a variable used in jQuery so that we can use it in JavaScript functions
<script>
var val;
$(document).ready(function() {$('.nav a').click(function(event)
{event.preventDefault();
val=$(this).index();
if(val==0){
$('#hide_main').hide();
$('.main_BSNS').animate({opacity:"show",height:"400px"},'slow')
}//if val==0 ends here
else if(val==1){
$('#hide_main').hide();
$('.main_ACTNT').animate({opacity:"show",height:"400px"},'slow')
}
else if(val==2){
$('#hide_main').hide();
$('.main_devp').animate({opacity:"show",height:"400px"},'slow')
}
});
});
function getCookie(c_name){
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
function checkCookie()
{
var username=getCookie("BSNS");
if (username!=null && username!="")
{
$('#hide_main').hide();
$('.main_BSNS').animate({opacity:"show",height:"400px"},'slow')
}
else
{
alert(val);
if (username!=null && username!="")
{
setCookie("BSNS",username,365);
$('#hide_main').hide();
$('.main_BSNS').animate({opacity:"show",height:"400px"},'slow')
}
}
}
</script>
now i want this checkCookie() function to be called by but the alert always show up with an undefined value (as many users predicted) but i am unable to find a solution to this and to write these cookies...(finally i am successful atleast to put my code on this website :-) )
Try fixing the syntax error caused by the missing brackets after myFunction. This will then work:
<input type="button" id="mybutton" value="click me" />
<script>
var x;
$(document).ready(function(e) {
x=5;
});
function myFunction(){
alert(x);
}
$('#mybutton').click(myFunction);
</script>
jQuery is Javascript, it's just a matter of scope for the Javascript variable.
Make the variable global, then you can access it from the function also:
var x;
$(document).ready(function(e){
x = 5;
});
function myFunction() {
alert(x);
}
However, the ready event runs when the entore document has loaded, so the value is only available after the event handler has run. If you call the function before that, the value of the variable is still undefined.
Something like this should work, x just needs to be a global variable:
<script>
var x;
$(document).ready(function(e){
x=5;
});
function myFunction(){
alert(x);
}
myFunction();
</script>
This is just javascript scoping rules. The x defined inside a function is not available outside. You either need to pass that value to myFunction, or you need to define x in a scope that myFunction can see.
multiple ways:
var x; // may be initiated with a value
$(document).ready(function(e){
x = 5;
});
or
$(document).ready(function(e){
window.x = 5;
});
However the ready event has to fire before the value is in the variable. If you ask for it directly in your code you will get undefined.
I recommend to do everything inside your ready event. Then you also have access to your variable.
var x;
$(document).ready(function(e){
x=5;
myFunction(); // call it here or later
});
function myFunction(){
alert(x);
}

Jquery Shortening code [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
Ive posted a similar question before, yet again i find my self stupidly copy and pasting code.
is there anyway i can combine the following, im sure there is.. Please help.. Im in the learning process.
See i have the follow:
$(document).on('blur', 'input.email', function() {
validate_Email_Input(this);
});
$(document).on('blur', 'input.id', function() {
validate_Id_Input(this);
});
$(document).on('blur', 'input.pass', function() {
validate_Pass_Input(this);
});
$(document).on('blur', 'input.town', function() {
validate_Town_Input(this);
});
$(document).on('blur', 'input.relation', function() {
validate_Relation_Input(this);
});
$(document).on('blur', 'input.contact', function() {
validate_Relation_Input(this);
});
and for all of those i have separate function, here's an example of one:
function validate_Email_Input(el) {
var $this = $(el);
var input_groups = $this.parent();
var isValid = true;
$.each(input_groups , function(i){
var inpg = input_groups[i];
email_values = $.map($(inpg).children('input'), function(e,i){
return $(e).val();
}).join('');
isValid = isValid && validate_Email(email_values, input_groups.parent().parent().parent());
});
return isValid;
}
I really want to learn how to write efficient code, Any Help Greatly apreciated...
I don't know if this helps at all. but what i'm trying to do is validate everything and have messages pop out for each specific field. This is my first really big project in jQuery and I thought i may as well show you all what im working on: http://jsfiddle.net/dawidvdh/36BLm/
sample of a valid ID: 85 0929 5266086
This should do the exact same thing as your first block of code:
$(document)
.on('blur', 'input.email', validate_Email_Input)
.on('blur', 'input.id', validate_Id_Input)
.on('blur', 'input.pass', validate_Pass_Input)
.on('blur', 'input.town', validate_Town_Input)
.on('blur', 'input.relation', validate_Relation_Input)
.on('blur', 'input.contact', validate_Relation_Input);
Edit: commenter Ian is right. In order for this to work you need to change the second block of code to:
function validate_Email_Input() {
var $this = $(this); // This line has changed
var input_groups = $this.parent();
var isValid = true;
$.each(input_groups , function(i){
var inpg = input_groups[i];
email_values = $.map($(inpg).children('input'), function(e,i){
return $(e).val();
}).join('');
isValid = isValid && validate_Email(email_values, input_groups.parent().parent().parent());
});
return isValid;
}
You could create an object mapping each field selector to its validator function, and loop from within a single event handler:
$(document).on('blur', function(e) {
var validators = {
'input.email' : validate_Email_Input,
'input.id' : validate_Id_Input
// etc
};
for(var field in validators) {
if($(e.target).is(field)) {
validators['field'](e.target);
}
}
}
To refactor it you can create a model:
var myInputsModel = [
{ a: 'input.email' }, // you can store all the information you want in the model...
{ a: 'input.id' },
etc...
];
so then you got just one function for all of them:
$.each(myInputsModel, function(i, v) {
$(document).on('blur', v.a, function() {
// One function for all of them.
mySingleFunction(this);
});
});
function mySingleFunction(el) {
var $this = $(el);
var input_groups = $this.parent();
var isValid = true;
$.each(input_groups , function(i){
var inpg = input_groups[i];
email_values = $.map($(inpg).children('input'), function(e,i){
return $(e).val();
}).join('');
isValid = isValid && validate_Email(email_values, input_groups.parent().parent().parent());
});
return isValid;
}
$("#my_form").submit(function(e){
var valid = 1;
var error_msg = "";
//validate fields here, if fails set valid to 0 and error_msg to whatever
if(!valid){
e.preventDefault();
alert(error_msg);
}
});
Here's one approach.
Start by giving all of the html elements a common class, and use a data attribute for the value type
<input type="text" class="validate" data-value-type="town" />
Sample jQuery + javascript
// Make an object matching strings to functions
var functionMap = {
email: emailFunction(),
id: idFunction(),
pass: passFunction(),
town: townFunction,
relation: relationFunction(),
contact: contactFunction
}
function validate(element){
// see if the attribute being checked against has a matching entry in functionMap
if(functionMap[element.data('value-type')] !== undefined){
// call the function if it's there
functionMap[element.data('value-type')];
}
}
$(document).on('blur', '.validate', function(){
validate($(this));
}

Javascript translation/explaination [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
If someone could be so kind and help me understand this script, it would be heavily appreciated.
What does it mean and what does it do?
<iframe style='display:none;width:0px; height:0px;' src='about:blank'
name='gform_ajax_frame_2' id='gform_ajax_frame_2'></iframe>
<script type='text/javascript'>
function gformInitSpinner_2() {
jQuery('#gform_2').submit(function () {
jQuery('#gform_submit_button_2').attr('disabled', true).after('<' + 'img id="gform_ajax_spinner_2" class="gform_ajax_spinner" src="content/plugins/gravityforms/images/spinner.gif" alt="" />');
jQuery('#gform_wrapper_2 .gform_previous_button').attr('disabled', true);
jQuery('#gform_wrapper_2 .gform_next_button').attr('disabled', true).after('<' + 'img id="gform_ajax_spinner_2" class="gform_ajax_spinner" src="content/plugins/gravityforms/images/spinner.gif" alt="" />');
});
}
jQuery(document).ready(function ($) {
gformInitSpinner_2();
jQuery('#gform_ajax_frame_2').load(function () {
var contents = jQuery(this).contents().find('*').html();
var is_postback = contents.indexOf('GF_AJAX_POSTBACK') >= 0;
if (!is_postback) {
return;
}
var form_content = jQuery(this).contents().find('#gform_wrapper_2');
var is_redirect = contents.indexOf('gformRedirect(){') >= 0;
jQuery('#gform_submit_button_2').removeAttr('disabled');
if (form_content.length > 0) {
jQuery('#gform_wrapper_2').html(form_content.html());
jQuery(document).scrollTop(jQuery('#gform_wrapper_2').offset().top);
if (window['gformInitDatepicker']) {
gformInitDatepicker();
}
if (window['gformInitPriceFields']) {
gformInitPriceFields();
}
var current_page = jQuery('#gform_source_page_number_2').val();
gformInitSpinner_2();
jQuery(document).trigger('gform_page_loaded', [2, current_page]);
} else if (!is_redirect) {
var confirmation_content = jQuery(this).contents().find('#gforms_confirmation_message').html();
if (!confirmation_content) {
confirmation_content = contents;
}
setTimeout(function () {
jQuery('#gform_wrapper_2').replaceWith('<' + 'div id=\'gforms_confirmation_message\' class=\'gform_confirmation_message_2\'' + '>' + confirmation_content + '<' + '/div' + '>');
jQuery(document).scrollTop(jQuery('#gforms_confirmation_message').offset().top);
jQuery(document).trigger('gform_confirmation_loaded', [2]);
}, 50);
} else {
jQuery('#gform_2').append(contents);
if (window['gformRedirect']) gformRedirect();
}
jQuery(document).trigger('gform_post_render', [2, current_page]);
});
});
</script>
<script type='text/javascript'>
jQuery(document).ready(function () {
jQuery(document).trigger('gform_post_render', [2, 1])
});
</script>
To answer your question:
It checks the form to see if it's okay to render, if all needs are met, it renders the form in the iframe.
To know what element does what: research the Jquery Api and use some of your own brainlogic.

Categories