keyCode 13 not working [duplicate] - javascript

This question already has answers here:
How to prevent ENTER keypress to submit a web form?
(29 answers)
Closed 7 years ago.
I have developed a search feature in my application. Users can search for streets by typing the address in an input box. Onkeyup, the a function is called that compares the input against a database full of addresses. The function gives back 5 suggestions which are showed below the inputbox like a sort of dropdownmenu. This works perfectly fine. The user can afterwards select one of the suggestions, which triggers another function.
What I want to implement now is that, when the user presses ENTER, the second function is automatically called with the first suggestion. I thought it would not be that difficult to program, but I'm facing some difficulties. When I press enter, the page refreshes instead of going to the function.
Here is my code:
<div id = "toolbar">
<form id ="suggestions">
<input type = "text" id = "insertText" autocomplete="off" onkeyup = "if(event.keyCode == 13) {SearchAddress(option1.text)} else {giveSuggestion()}" onfocus='showOptions()'
<option class="option" id = "option1" onmousedown = "searchAddress(option1.text)"></option>
<option class="option" id = "option2" ... </option>
</form>
</div>
CSS
#toolbar {
position: fixed;
width: 100%;
height: 25px;
top: 0;
left: 0;
padding: 5px 10px;
background: #ccc;
border-bottom: 1px solid #333;
}
#suggestions {
-moz-box-sizing: border-box;
box-sizing: border-box;
position: absolute;
left: 310px;
top: 5px;
background-color: white;
font-size: 12px;
}
.option{
display:none;
cursor: default;
padding: 0px 3px;
}
Any suggestions?

When you hit enter the browser tries to submit the form.
So, there are two possible solutions:
Remove form tag, if you don't need to send any data from it to the backend.
Add onsubmit="return false;" to the form tag.

I guess the browser didn't know what event is So......
<input type = "text"
id = "insertText"
autocomplete="off"
onkeyup = "function(event){if(event.keyCode == 13)
{SearchAddress(option1.text)}
else {giveSuggestion()}"
onfocus='showOptions()'}" />

The default behavior of form will refresh the page, so place replace the form tag to div, and handle the form submit yourself use library like jQuery or vanilla XMLHttpRequest object.

Related

Can you turn a CSS background-image into a submit button using JavaScript? [duplicate]

This question already has answers here:
How do I add a "search" button in a text input field?
(7 answers)
Closed 5 years ago.
Here is the HTML form:
<form method="post" action="search.php">
<input type="text" id="inputSearch"/>
</form>
And some CSS:
#inputSearch {
padding:18px 15px 18px 52px;
font-size:1rem;
color:#1f5350;
border:none;
/*defining background image as a search symbol*/
background: #7accc8 url(search.png) 8px 14px no-repeat;
background-size:25px 26px;
}
The search icon is just a static image. Using JavaScript, how can I grab the CSS background-image and use it to create a clickable submit button without adding further HTML code?
You can wrap your search icon in <a></a> tags, that way your image will be clickable and can take the user to the page you want once he clicks on it: Here's an example:
<div class="maindiv">
<form id="myform" name="myform" method="post" action="schitems.php">
<input type="search" id="itemcd" name="itemcd" class="inputfields" placeholder="Type an Ingredient..." />
<img src="search_icon.jpg" alt="search">
</form>
</div>
What you're trying to achieve can't actually be accomplished with raw CSS; you need to use JavaScript and attach a click event handler to the element.
Unfortunately, considering you're making use of background-image, your image is essentially 'part of' the whole <input> element itself, and as far as I'm aware, you can't separate out the click functionality (without making use of a separate element for the image).
Having said that, you can make it so that the form submits when any part of the <input> is clicked on with the following. This can be improved by double-checking that there is actually content entered into the input before allowing the form submission to fire:
var form = document.getElementById('myform');
var input = document.getElementById('itemcd');
input.onclick = function() {
if (this.value.length > 0) {
form.submit();
}
}
#myform {
width: 260px;
margin: 0 auto;
}
input[type="search"] {
padding: 18px 15px 18px 52px;
font-size: 1rem;
color: #1f5350;
/*removing boder from search box*/
border: none;
/*defining background image as a search symbol*/
background-image: url(http://placehold.it/100);
background-repeat: no-repeat;
/*background-size*/
-webkit-background-size: 25px 26px;
-moz-background-size: 25px 26px;
-o-background-size: 25px 26px;
background-size: 25px 26px;
/*positioning background image*/
background-position: 8px 14px;
/*changing background color form white*/
background-color: #7accc8;
outline: 0;
}
/*now using placeholder property to change color of placholder text and making it consitent accross the browser by use of prefix*/
input[type="search"]::-webkit-input-placeholder {
color: #b1e0de;
}
input[type="search"]:-moz-placeholder {
/* Firefox 18- */
color: #b1e0de;
}
input[type="search"]::-moz-placeholder {
/* Firefox 19+ */
color: #b1e0de;
}
input[type="search"]:-ms-input-placeholder {
/* interner explorer*/
color: #b1e0de;
}
<div class="maindiv">
<form id="myform" name="myform" method="post" action="schitems.php">
<input type="search" id="itemcd" name="itemcd" class="inputfields" placeholder="Type an Ingredient..." />
</form>
</div>
Hope this helps! :)

"old" phones do not show the checkbox checkmark, when is checked via javascript

Good day all.
I've a page with a form, there is a option (a checkbox) that MUST be checked in order to submit the form, so basically there is a simple javascript like this:
function checkbox_tick_action (){
$("#mt-container #option").prop( 'checked',true );
$("#mt-container #option").attr('checked','checked');
console.log("ticked");
}
binded on the submit event.
This work pretty fine, but on some mobiles, the checkbox isn't updated, so this happen:
the form is submitted (the checkbox IS ticked, but shown as unticked).
landing on the next page, and hitting the back button, the checkbox is now showed as ticked.
I have done a number of test and I'm prett sure is a matter of "updating the DOM" or something that simply does not render the new "visual" of the checkbox.
anyone has a hint on how to solve this issue?
is there a way to force the render of an element, via js?
Note that this is actually working on most devices.
one of the devices that has this issue is Samsung ACE, using the stock browser.
all the phones that has this issue, are somehow dated.
the issue is present on android phones mostly, with 2.3.3 or less.
I have try this:
function checkbox_tick_action (){
$("#mt-container #option").prop( 'checked',true );
$("#mt-container #option").attr('checked','checked');
var opt = document.getElementById('option');
opt.style.display='none';
opt.offsetHeight;
opt.style.display='block';
console.log("tick 2");
with no luck actually.
the HTML is:
<input type="checkbox" name="option" id="option" value="true" data-tid="checkBox">
The CSS:
#mt-container input:not(checked) + label:before {
border: 1px solid #3E3E3E;
background-color: #EFEFEF;
content: "\00a0";
display: inline-block;
width: 14px;
height: 14px;
font-size:15px;
line-height: 15px;
}
#mt-container input:checked + label:before {
border: 1px solid #3E3E3E;
background-color: #EFEFEF;
color: #3E3E3E;
content: "\2714";
font-size: 15px;
text-align: center;
line-height: 15px;
font-weight: bold;
}
#mt-container input:checked, #mt-container input:not(checked) {
position:absolute;
top:-500px;
left:-900px;
}
If you are using Google material design, add "is-checked" class to element's
parent, as
$("#option").parent().addClass("is-checked");
to render visualisation. hope this will work!

Javascript Logic in Extending Search Bar

I've created an expanding search bar: You click on the magnifying glass the input extends out and to the right, click it again and it closes. (See Fiddle Below).
I'm new to the world of JS and I thought this would be a great opportunity to implement some logic. Here's what I;m trying to do:
If the search bar is open and the inner.html is empty, if you click the "search" magnifying glass, I want to prevent the default submission of the form and simply close the search bar
If there is text, I want the form to be submitted.
Right now I've got the elements layered in such a way as to when you click the "search" button for the first time, the bar extends and the z-index of the button drops to one where the actual submit button is higher, but I want to control the functionality a little more.
What I've tried:
I tried creating a function that added an event listener that said, basically, if the bar has a width of 700px (the extended length) and the inner html is empty, bring the z-index of the extend button up back higher than the submit simply close the form. But I can't seem to work the logic out properly.
I'm wondering how in JS you can control the z-index.
Here is the code I tried and did not work. I tried something simply like just alerting when the task I wanted to watch for was done first but it doesn't seem to be working.
Any help would be wonderful.
Code:
HTML:
<div id="wrap">
<form id="myForm">
<input id="search" name="search" type="text" placeholder="What are we looking for?" />
<input id="search_submit" value="" type="submit">
</form>
</div>
CSS:
#wrap
{
margin: 50px 100px;
display: inline-block;
position: relative;
height: 60px;
float: right;
padding: 0;
}
input[type="text"]
{
height: 40px;
font-size: 35px;
border: none;
outline: none;
color: #555;
padding-right: 60px;
position: absolute;
width: 0px;
top: 0;
right: 0;
background: none;
z-index: 4;
cursor: pointer;
transition: width .4s ease-in-out;
}
input[type="text"]:focus
{
width: 700px;
z-index: 1;
border-bottom: 1px solid #bbb;
cursor: text;
}
input[type="submit"]
{
position: absolute;
height: 60px;
width: 60px;
display: inline-block;
float: right;
background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAMAAABg3Am1AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAADNQTFRFU1NT9fX1lJSUXl5e1dXVfn5+c3Nz6urqv7+/tLS0iYmJqampn5+fysrK39/faWlp////Vi4ZywAAABF0Uk5T/////////////////////wAlrZliAAABLklEQVR42rSWWRbDIAhFHeOUtN3/ags1zaA4cHrKZ8JFRHwoXkwTvwGP1Qo0bYObAPwiLmbNAHBWFBZlD9j0JxflDViIObNHG/Do8PRHTJk0TezAhv7qloK0JJEBh+F8+U/hopIELOWfiZUCDOZD1RADOQKA75oq4cvVkcT+OdHnqqpQCITWAjnWVgGQUWz12lJuGwGoaWgBKzRVBcCypgUkOAoWgBX/L0CmxN40u6xwcIJ1cOzWYDffp3axsQOyvdkXiH9FKRFwPRHYZUaXMgPLeiW7QhbDRciyLXJaKheCuLbiVoqx1DVRyH26yb0hsuoOFEPsoz+BVE0MRlZNjGZcRQyHYkmMp2hBTIzdkzCTc/pLqOnBrk7/yZdAOq/q5NPBH1f7x7fGP4C3AAMAQrhzX9zhcGsAAAAASUVORK5CYII=) center center no-repeat;
border: none;
outline:none;
top: -15px;
right: 0;
z-index: 2;
cursor: pointer;
transition: all .4s ease;
}
JS
var search = document.getElementById("myForm").search;
var search_submit = document.getElementById("myForm").search_submit;
function showOpen()
{
if(search.style.width=="700px")
{
alert("OPEN!");
}
};
search.addEventListener("click", showOpen);
showOpen();
HERE IS THE FIDDLE: https://jsfiddle.net/theodore_steiner/7begmkf3/37/
Your issue can be solved using a few basic JavaScript elements (if you're looking to get into basic logic, these are important to know). The JS uses onsubmit, onclick, and some basic form logic. Basically, when you try to submit the form it checks if the form is empty, and if it is, the program refuses to submit the code. I added the new JavaScript to the HTML file:
<script>
function check(){
value = document.forms["myForm"]["search"].value;
if(value == "" || value == null){
alert("please enter a search term");
return false;
}else{
document.getElementById("myForm").submit();
}
}
</script>
<div id="wrap">
<form id="myForm" onsubmit="return check()">
<input id="searchBar" name="search" type="text" placeholder="What are we looking for?" />
<input id="search_submit" value="" type = "submit">
</form>
</div>
fiddle: https://jsfiddle.net/q1L3Lstx/1/
It might also help in the future to look at the required element: http://www.w3schools.com/tags/att_input_required.asp
I saw a couple of issues with the code.
search and search_submit are pointing to the wrong items they can be like this:
var search = document.getElementById("search");
var search_submit = document.getElementById("search_submit");
You could call a function on submit. like this:
<form id="myForm" onsubmit="myFunction(event)">
finally you can work your code inside that function:
function myFunction(e){
if(search.value.length <= 0){
e.preventDefault();
alert('empty');
}
}

jQuery custom checkboxes + hidden html checkbox

I'm making a grid of divs that can be toggled on and off. I need to post the values of these toggled divs to a database.
Currently I have jQuery waiting for clicks on the divs and then changing checkbox values on a hidden checkbox element...
$('.icon').click(function(){
var checkValue = $(this).attr("data-c");
// Then tick hidden checkbox where data-c = checkbox
});
As I end up posting this data with ajax, is there a better way to do this?
Here's what it looks like:
You actually don't need JS.
Use a <label> elements to wrap your checkbox and a span.
Change the style of that inner span using the input:checked next sibling selector +:
label.icon span{
cursor: pointer;
display: inline-block;
width: 75px;
height: 75px;
background:url(http://i.stack.imgur.com/ceycQ.jpg) no-repeat;
border: 3px solid #0186C9;
border-radius: 12px;
}
label.icon input{ /* hide the checkbox */
position: absolute;
visibility: hidden;
}
label.icon input:checked + span{ /* when input is checked */
background-position: 0 -75px;
}
<form action="">
<label class="icon">
<input type="checkbox" name="dog">
<span></span>
</label>
</form>
on form submit you'll submit all the correct data without a single line of JS
I've found a similar question here: Jquery Use Image As CheckBox
As an alternative to storing the value in a check box you could store it in a object? For example:
window.icons = {};
$('.icon').click(function() {
var id = $(this).data('identifier');
window.icons[id] = !!window.icons[id];
});
Also check out this example for a similar use http://jsfiddle.net/bdTX2/

how to customize html for django form

I am using an html template for my website, and wants to collect information to my django backend. Specifically, I want to return the value of email address from this part of the code
<input type="text" placeholder="Email" value="" style="height: 30px; width: 250px; border: 2px solid grey; padding: 7px; margin-top: 10px; margin-bottom: 10px; font-size: 20px;">
if i put {{%form.email%}} in to value="", it'll write <input id= inside the box, and "> outside of the box.
if I put {{%form.email%} behind this part of html code, it will generate another box. But i only want to use this box.
How should i do it?
Usually you want to generate a field by using a Django-Form Class. There you can also customize your entire field: For your example you would have to create a class like this in your forms.py
class EmailForm(forms.Form)
email = forms.CharField(widget=forms.EmailInput(attrs={'class': 'email-input',
'placeholder': 'Email'})
You can also use
{'style': 'height: 30px; width: 250px; border: 2px solid grey; padding: 7px; margin-top: 10px; margin-bottom: 10px; font-size: 20px;'}
instead of {'class': 'email-input'} for your style, but it's usually better to use a css class.
The email in your class is basically your entire email field but it automatically generates a name and id so it's easier to use.
Now if you want the value of your field in the backend you have to do a GET or POST request (I think in this case POST). You will get the value by using the following pattern in the method in which you want to handle the recieved data: (works but not optimal) field_value = request.POST.get('fieldname') or even better as Daniel pointed out in the comments with field_value = form.cleaned_data['fieldname'].
So In your case it would be something like this: email = form.cleaned_data['email']. This will return the value that was typed into the field for later backend-use.

Categories

Resources