Make it so 'Go/Enter' key is pressable - javascript

I have a basic form which makes it so the user cannot leave the input field empty before the form posts the page. It also prevents the user from entering gibberish and requires them to only enter numbers, but this also blocks all keys that aren't numbers including the Go/Enter on mobile keyboards. My question is, is there a way to make it so that the user has to enter only numbers, but also be able to press Go after they have entered the field?
FIDDLE:http://jsfiddle.net/schermerb/nX8Hx/
Currently a user has to input a zip THEN tap back on the screen and THEN click submit.
$(document).ready(function () {
$("#quantity").keypress(function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
$("#errmsg").html("Enter Valid Zip!").show().fadeOut("5000");
return false;
}
});
});
var initVal = "Have a good name for it? Enter Here";
$(document).ready(function () {
$(".submit-name").attr("disabled", "true");
$(".recipe-name").blur(function () {
if ($(this).val() != initVal && $(this).val() != "") {
$(".submit-name").removeAttr("disabled");
} else {
$(".submit-name").attr("disabled", "true");
}
});
});
input {
width: 100%;
background: #FFFFFF;
border-radius: 4px;
border: 2px solid #acd50b;
padding: 10px 15px;
text-align: center;
-webkit-appearance: none;
color: #999999;
font-size: 11px;
}
input[type="focus"] {
outline: none;
}
input[type="submit"] {
border-radius: 4px;
border: 2px solid #2d8b1b;
-webkit-appearance: none;
background: #acd50b;
padding: 6px 10px;
color: #444444;
width: 100%;
font-size: 18px;
cursor:pointer;
}
.box {
width: 85px;
}
.boxtwo {
width: 160px;
}
<form action="google.html" method="get" id="recipename">
<div class="box">
<input onFocus="this.value=''" type="text" value="Enter Your Zip" placeholder="Enter Your Zip" /><span id="errmsg"></span>
</div>
<div class="boxtwo">
<input type="submit" value="Compare" id="register" disabled value="Compare" class="submit-name" />
</div>
</form>

It would be better to use keydown and test the resulting value and revert it rather than only allowing certain characters to be inserted.
$("#quantity").keydown(function (e) {
var self = this;
var tempVal = this.value;
setTimeout(function () {
if (!isValidZip(self.value)) {
self.value = tempVal;
}
}, 0);
});
function isValidZip(zip) {
return /^[0-9]{1,5}$/.test(zip);
}
http://jsfiddle.net/nX8Hx/3/
This could also be done with keyup or keypress, however keydown makes it happen much quicker and allows you to easily get the previous value.
Doing it this way avoids the issue of preventing the done key by not testing which key is pressed. It's also easily expandable by simply changing the regexp to match a different kind of zip code.

Related

onmouseover not working in option [duplicate]

I am trying to show a description when hovering over an option in a select list, however, I am having trouble getting the code to recognize when hovering.
Relevant code:
Select chunk of form:
<select name="optionList" id="optionList" onclick="rankFeatures(false)" size="5"></select>
<select name="ranks" id="ranks" size="5"></select>
Manipulating selects (arrays defined earlier):
function rankFeatures(create) {
var $optionList = $("#optionList");
var $ranks = $("#ranks");
if(create == true) {
for(i=0; i<5; i++){
$optionList.append(features[i]);
};
}
else {
var index = $optionList.val();
$('#optionList option:selected').remove();
$ranks.append(features[index]);
};
}
This all works. It all falls apart when I try to deal with hovering over options:
$(document).ready(
function (event) {
$('select').hover(function(e) {
var $target = $(e.target);
if($target.is('option')) {
alert('yeah!');
};
})
})
I found that code while searching through Stack Exchange, yet I am having no luck getting it to work. The alert occurs when I click on an option. If I don't move the mouse and close the alert by hitting enter, it goes away. If I close out with the mouse a second alert window pops up. Just moving the mouse around the select occasionally results in an alert box popping up.
I have tried targeting the options directly, but have had little success with that. How do I get the alert to pop up if I hover over an option?
You can use the mouseenter event.
And you do not have to use all this code to check if the element is an option.
Just use the .on() syntax to delegate to the select element.
$(document).ready(function(event) {
$('select').on('mouseenter','option',function(e) {
alert('yeah');
// this refers to the option so you can do this.value if you need..
});
});
Demo at http://jsfiddle.net/AjfE8/
try with mouseover. Its working for me. Hover also working only when the focus comes out from the optionlist(like mouseout).
function (event) {
$('select').mouseover(function(e) {
var $target = $(e.target);
if($target.is('option')) {
alert('yeah!');
};
})
})
You don't need to rap in in a function, I could never get it to work this way. When taking it out works perfect. Also used mouseover because hover is ran when leaving the target.
$('option').mouseover(function(e) {
var $target = $(e.target);
if($target.is('option')) {
console.log('yeah!');
};
})​
Fiddle to see it working. Changed it to console so you don't get spammed with alerts. http://jsfiddle.net/HMDqb/
That you want is to detect hover event on option element, not on select:
$(document).ready(
function (event) {
$('#optionList option').hover(function(e) {
console.log(e.target);
});
})​
I have the same issue, but none of the solutions are working.
$("select").on('mouseenter','option',function(e) {
$("#show-me").show();
});
$("select").on('mouseleave','option',function(e) {
$("#show-me").hide();
});
$("option").mouseover(function(e) {
var $target = $(e.target);
if($target.is('option')) {
alert('yeah!');
};
});
Here my jsfiddle https://jsfiddle.net/ajg99wsm/
I would recommend to go for a customized variant if you like to ease
capture hover events
change hover color
same behavior for "drop down" and "all items" view
plus you can have
resizeable list
individual switching between single selection and multiple selection mode
more individual css-ing
multiple lines for option items
Just have a look to the sample attached.
$(document).ready(function() {
$('.custopt').addClass('liunsel');
$(".custopt, .custcont").on("mouseover", function(e) {
if ($(this).attr("id") == "crnk") {
$("#ranks").css("display", "block")
} else {
$(this).addClass("lihover");
}
})
$(".custopt, .custcont").on("mouseout", function(e) {
if ($(this).attr("id") == "crnk") {
$("#ranks").css("display", "none")
} else {
$(this).removeClass("lihover");
}
})
$(".custopt").on("click", function(e) {
$(".custopt").removeClass("lihover");
if ($("#btsm").val() == "ssm") {
//single select mode
$(".custopt").removeClass("lisel");
$(".custopt").addClass("liunsel");
$(this).removeClass("liunsel");
$(this).addClass("lisel");
} else if ($("#btsm").val() == "msm") {
//multiple select mode
if ($(this).is(".lisel")) {
$(this).addClass("liunsel");
$(this).removeClass("lisel");
} else {
$(this).addClass("lisel");
$(this).removeClass("liunsel");
}
}
updCustHead();
});
$(".custbtn").on("click", function() {
if ($(this).val() == "ssm") {
$(this).val("msm");
$(this).text("switch to single-select mode")
} else {
$(this).val("ssm");
$(this).text("switch to multi-select mode")
$(".custopt").removeClass("lisel");
$(".custopt").addClass("liunsel");
}
updCustHead();
});
function updCustHead() {
if ($("#btsm").val() == "ssm") {
if ($(".lisel").length <= 0) {
$("#hrnk").text("current selected option");
} else {
$("#hrnk").text($(".lisel").text());
}
} else {
var numopt = +$(".lisel").length,
allopt = $(".custopt").length;
$("#hrnk").text(numopt + " of " + allopt + " selected option" + (allopt > 1 || numopt === 0 ? 's' : ''));
}
}
});
body {
text-align: center;
}
.lisel {
background-color: yellow;
}
.liunsel {
background-color: lightgray;
}
.lihover {
background-color: coral;
}
.custopt {
margin: .2em 0 .2em 0;
padding: .1em .3em .1em .3em;
text-align: left;
font-size: .7em;
border-radius: .4em;
}
.custlist,
.custhead {
width: 100%;
text-align: left;
padding: .1em;
border: LightSeaGreen solid .2em;
border-radius: .4em;
height: 4em;
overflow-y: auto;
resize: vertical;
user-select: none;
}
.custlist {
display: none;
cursor: pointer;
}
.custhead {
resize: none;
height: 2.2em;
font-size: .7em;
padding: .1em .4em .1em .4em;
margin-bottom: -.2em;
width: 95%;
}
.custcont {
width: 7em;
padding: .5em 1em .6em .5em;
/* border: blue solid .2em; */
margin: 1em auto 1em auto;
}
.custbtn {
font-size: .7em;
width: 105%;
}
h3 {
margin: 1em 0 .5em .3em;
font-weight: bold;
font-size: 1em;
}
ul {
margin: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>
customized selectable, hoverable resizeable dropdown with multi-line, single-selection and multiple-selection support
</h3>
<div id="crnk" class="custcont">
<div>
<button id="btsm" class="custbtn" value="ssm">switch to multi-select mode</button>
</div>
<div id="hrnk" class="custhead">
current selected option
</div>
<ul id="ranks" class="custlist">
<li class="custopt">option one</li>
<li class="custopt">option two</li>
<li class="custopt">another third long option</li>
<li class="custopt">another fourth long option</li>
</ul>
</div>

Javascript logic not working

The if condition is not working while the else if and else are working:
function userchk() {
var un = $('#user_name').val();
if (un.length < 3 && un.length != 0) {
$("#validateUser").html("<span style='color:red' class='status-not-available'>User Name Shoul Be Greater Then 3.</span>");
}
else if (un.length == 0) {
$('#validationUser').html("<span style='color:red' class='status-not-available'> User Name Cannot Be Empty.</span>");
}
else {
$('#validationUser').html("");
}
}
$('#btnTest').on('click', function() {
userchk();
});
input {
width: 100%;
margin-top: 20px;
float: left;
}
button {
font-size: 20px;
background-color: #555;
color: #fff;
padding: 10px 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnTest">Test userchk()</button>
<input type="text" name="user_name" id="user_name" onBlur="userchk()" class="form-control" placeholder="Username" />
<div id="validationUser"></div>
Your if condition results in an element with id #validateUser being selected and manipulated.
Your else if and else target #validationUser
The Javascript logic conditions are sound but you are not getting your expected results because you are targeting a different element in your if block.

How do I transform a word in a html textbox to a "tag" with jQuery?

I want to program a fancy searchbox.
Everytime when you type a word and then press the spacebar, the word should be transformed to a "tag". With "tag" I mean following:
The tags you can see here are from my profile settings from stackoverflow. Here, a tag is created by pressing the "add"-Button. But I want the word to become a tag not by pressing a button, but everytime I press the spacebar.
Do you have any solutions for my problem?
I've searched for a long time in google, but i haven't found anything!
Thank you for your help!
:D
https://jsfiddle.net/geop94u7/
Somewhat robust, can be packaged for re-use with some consideration (scoping, multi-instance, etc.).
First, the markup:
<div id="tags" class="cf"></div>
<input type="text" id="tagname" />
Then the JS, preventing duplicates, and allowing removal of already selected tags (which can be re-selected then).
$('#tagname').keypress(function(e) {
var $t = $(e.target),
tmap = $t.data('tmap') || {},
n = e.keyCode || e.which,
val;
$t.data('tmap', tmap);
if (n === 32) {
val = $.trim($t.val());
if (val !== '' && tmap[val] === undefined) {
tmap[val] = 1;
$('#tags').append($('<div>').addClass('tag').html(val));
$t.val('');
}
}
});
$('#tags').on('click', '.tag', function(e) {
var $t = $(e.target);
txt = $.trim($t.text());
$t.remove();
delete $('#tagname').data('tmap')[txt];
});
Lastly, some run of the mill CSS with a delete indicator:
#tags {
width: 100%;
padding: 10px;
float: none;
clear: both;
}
.tag {
float: left;
margin: 5px;
padding: 5px;
background: #efefef;
cursor: pointer;
border: 1px solid #e0e0e0;
}
.tag::after {
content: '\2612';
float: right;
display: block;
margin: -2px 0 0 10px;
}
You're better off using a robust plugin (there are quite a few) if rebuilding from scratch isn't a mandate.
Here's a quick fiddle https://jsfiddle.net/lexicalnoscope/4ouh7m97/. I kind of hate using jQuery for stuff like this, though, so it's in plain javascript. The script portion looks like this:
var output = document.getElementById('output'),
input = document.querySelector('input');
input.onkeyup = function(e){
if(e.keyCode == 32) { //check for spacebar
var tag = document.createElement('span');
tag.className = "tag";
tag.textContent = input.value.trim();
input.value = "";
output.appendChild(tag)
}
}

Credit cards types for jessepollak's JQuery.Card.js

I am using jquery.card.js from jessepollak. It is awesome.
If anyone has experience with it, could you please tell me if there is an option to choose what types of credit card you want to support?
e.g.
//This is how I would like it to be...
var card = new Card({
supportedCardTypes: 'Visa, Master'; //I don't want DC or AMEX etc...
});
Is there any options like that? How do I achieve it?
Thank you.
Answer ------------------------------------------------------------
Turns out, only changing cardTypes as TMan suggested didn't work. But it is not about the fish, it is about giving me the idea of fishing. Following TMan's idea hacking into the script, I found adding this line would work:
Card.prototype.handlers = {
setCardType: function($el, e) {
//my modification here to support only Visa and Master!!
var cardType = e.data === 'mastercard' || e.data === 'visa' ? e.data : 'unknown';
//end of my modification!!
if (!QJ.hasClass(this.$card, cardType)) {
QJ.removeClass(this.$card, 'jp-card-unknown');
QJ.removeClass(this.$card, this.cardTypes.join(' '));
QJ.addClass(this.$card, "jp-card-" + cardType);
QJ.toggleClass(this.$card, 'jp-card-identified', cardType !== 'unknown');
return this.cardType = cardType;
}
},
You can just hack the library source code, quick and dirty NOT the best idea, or do something to initialise the handlers your way in your own code.
Thanks again.
Great ideas all around. Here's a way to take your addition to the handler and override it without having to hack at the library. This will persist future changes much better.
var setCardTypeOrig = Card.prototype.handlers.setCardType;
Card.prototype.handlers.setCardType = function($el, e) {
var allowedCards = ['mastercard','visa'];
if (allowedCards.indexOf(e.data) < 0) e.data = 'unknown';
setCardTypeOrig.call(this, $el, e);
}
Demo in Stack Snippets
var setCardTypeOrig = Card.prototype.handlers.setCardType;
Card.prototype.handlers.setCardType = function($el, e) {
var allowedCards = ['mastercard','visa'];
if (allowedCards.indexOf(e.data) < 0) e.data = 'unknown';
setCardTypeOrig.call(this, $el, e);
}
var card = new Card({ form: '.form-container form', container: '.card-wrapper' })
.form-container {
margin-top: 20px;
}
.form-container input {
font-family: 'Helvetica Neue', Helvetica, Helvetica, Arial, sans-serif;
float: left;
}
.form-container input.col-6 {
width: 50%
}
.form-container input.col-3 {
width: 25%
}
.form-container input[type="text"] {
background-color: #fff;
border: 1px solid #cccccc;
font-size: 0.875rem;
margin: 0 0 1rem 0;
padding: 0.5rem;
height: 2.3125rem;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.form-container .button {
cursor: pointer;
position: relative;
text-decoration: none;
text-align: center;
font-size: 0.875rem;
margin: 0 0 1rem 0;
padding: 0.5rem;
height: 2.3125rem;
color: #fff;
background-color: #008CBA;
border-width: 0;
}
.form-container .button:hover,
.form-container .button:focus {
background-color: #007295;
}
<script src="https://rawgit.com/jessepollak/card/master/lib/js/card.js"></script>
<div class="demo-container">
<div class="card-wrapper"></div>
<div class="form-container">
<form action="">
<input placeholder="Card number" type="text" name="number" class="col-6"/>
<input placeholder="Full name" type="text" name="name" class="col-6"/>
<input placeholder="MM/YY" type="text" name="expiry" class="col-3"/>
<input placeholder="CVC" type="text" name="cvc" class="col-3"/>
<input type="submit" value="Submit" class="button col-6"/>
</form>
</div>
</div>
To test it, you can look at the card payment definitions:
mastercard (55*) - works ✓
visa (4*) - works ✓
amex (37*) - doesn't ✓
Based on the Coffeescript file, I think your best bet would be to fork the library and then remove the cards you don't want to support from the cardTypes array so that all other numbers would show up as undefined.
https://github.com/jessepollak/card/blob/master/src/coffee/card.coffee
Or the following line in card.js:
https://github.com/jessepollak/card/blob/master/lib/js/card.js#L1134
Card.prototype.cardTypes = ['jp-card-amex', 'jp-card-dankort', 'jp-card-dinersclub',
'jp-card-discover', 'jp-card-jcb', 'jp-card-laser', 'jp-card-maestro',
'jp-card-mastercard', 'jp-card-unionpay', 'jp-card-visa', 'jp-card-visaelectron'];
You'll also probably want to modify the cardTemplate variable to remove the DOM nodes that no longer apply:
https://github.com/jessepollak/card/blob/master/src/coffee/card.coffee#L36

Make contents of div scroll down with overflow

I have created a small chat system for a project I am making. The chat is functioning well. However, I cannot figure out how to make it so the div stays at the bottom of the chat, rather than having to scroll down to read the last thing someone said.
I am referring to another similar question posted on here for guidance. How to keep a div scrolled to the bottom as HTML content is appended to it via jquery, but hide the scroll bar?
But it still will not work for me. The chat is then stored in a chat.txt file. Each line is surrounded in tags. The following is the code I am using.
js in header:
$container = $('#chat-area');
$container[0].scrollTop = $container[0].scrollHeight;
$('#sendie').keypress(function (e) {
if (e.which == 13) {
$container = $('#chat-area');
$container.append('<p>' + e.target.value + '</p>');
$container.animate({ scrollTop: $container[0].scrollHeight }, "slow");
}
});
chat.php:
<script type="text/javascript">
// strip tags
name = name.replace(/(<([^>]+)>)/ig,"");
// display name on page
$("#name-area").html("You are: <span>" + name + "</span>");
// kick off chat
var chat = new Chat();
$(function() {
chat.getState();
// watch textarea for key presses
$("#sendie").keydown(function(event) {
var key = event.which;
//all keys including return.
if (key >= 33) {
var maxLength = $(this).attr("maxlength");
var length = this.value.length;
// don't allow new content if length is maxed out
if (length >= maxLength) {
event.preventDefault();
}
}
});
// watch textarea for release of key press
$('#sendie').keyup(function(e) {
if (e.keyCode == 13) {
var text = $(this).val();
var maxLength = $(this).attr("maxlength");
var length = text.length;
// send
if (length <= maxLength + 1) {
chat.send(text, name);
$(this).val("");
} else {
$(this).val(text.substring(0, maxLength));
}
}
});
});
</script>
<p id="name-area"></p>
<div id="chatWrap"><div id="chat-area"></div></div>
<form id="send-message-area">
<p>Your message: </p>
<textarea id="sendie" maxlength = '100' ></textarea>
</form>
</div>
css:
#pageWrap
{
position: fixed;
display: block;
right: 0;
bottom: 0;
background: #8B1918;
box-shadow: 0px 0px 12px #333;
transition: height .5s;
}
#pageWrap p
{
color: white;
font-family: arial;
margin-left: 5px;
margin-bottom: 4px;
}
#chatWrap
{
width: 200px;
height: 200px;
overflow: scroll;
overflow-x:hidden;
box-shadow: 1px 1px 10px #333 inset;
color: white;
font-family: arial;
font-size: 14px;
}
#chat-area
{
padding-left: 11px;
}
#sendie
{
resize: none;
display: block;
width: 92%;
margin-left: auto;
margin-right: auto;
margin-bottom: 6px;
}
I got it (partially) working for you. Here are the issues I discovered:
Try not to name variables starting with $ - it creates unnecessary confusion.
You didn't declare $container as var, so you're using a variable before declaring it.
jQuery supports 99% of everything you can do with plain Javascript, but makes it better. Wherever possible, I changed your code to use jQuery instead.
I'm not sure about e.target.value, but $('#sendie').val() works just as well.
You definitely needed to wrap this in the body onload function.
You want to add e.preventDefault(); in the event handler so that it doesn't put a return character in the box.
You didn't clear the input textarea (with jQuery it's just $('#sendie').val('');).
The font color of the chat message area was white (at least on JSFiddle it was). Messages were invisible due to this.
Here's a fiddle demonstrating everything working (as far as I know) - http://jsfiddle.net/U9XAv/
And here's the updated Javascript:
$(function()
{
var container = $('#chat-area');
container.css('scrollTop', container.css('scrollHeight'));
$('#sendie').keydown(function (e)
{
if (e.which == 13)
{
container.append('<p>' + $(this).val() + '</p>')
.animate({ scrollTop: container[0].scrollHeight) }, "slow");
$(this).val('');
e.preventDefault();
}
});
});
And the CSS I changed:
#chat-area
{
padding-left: 11px;
color: black;
}

Categories

Resources