Issue with adding a list item using JQuery - javascript

I have this code which was working earlier. Then I started putting the code into small small functions and now it is not working. I can see that it is adding list item but automatically removing it also. Please guide -
<body>
<header>
<h1>Your Ration List</h1>
</header>
<div id="container">
<form class="shopList-form">
<input id="add" type="text" placeholder="Type new item here" />
</form>
<ul id="item_list">
<li id="base" class="hidden">
<form>
<input class="check" type="checkbox" /> <span class="item">Item</span>
</form>
<button class="delete_item hidden"></button>
</li>
</ul>
JQuery code -
$(document).ready(function () {
/* Get user input */
getItem();
function getItem() {
$('input#add').keydown(function (event) {
if (event.keyCode == 13) {
addItem();
}
});
}
function addItem() {
$('li#base').clone(true).appendTo('#item_list').removeAttr('id').removeClass('hidden');
$('ul#item_list>li:last>form>span').text($('input#add').val());
$('input#add').val("");
}
});
Full code can be found at this JSFiddle -
http://jsfiddle.net/varunksaini/Zjxq5/8/

Since it is a form, pressing enter not only triggers your function but also submits the form (since there is no action it submits to itself) so the page actually refreshes and that is why the new <li> is gone.
All you need to do is add return false to getItem.
see fiddle: http://jsfiddle.net/Zjxq5/9/

The problem you have with your script is that you are using a form and when you press enter it submits the form to the server and reloads the page. You can use the preventDefault() function to avoid that.
$('input#add').keydown(function (event) {
if (event.keyCode == 13) {
event.preventDefault();
addItem();
}
});
Example: http://jsfiddle.net/rdnKq/1/

Related

Meteor: delete by text property not working

I am following the meteor tutorial, and along with adding a form to add a task, I made a form to delete a task by its text value as well.
Template.body.events({
"submit .new-task": function (event) {
// Prevent default browser form submit
event.preventDefault();
// Get value from form element
var text = event.target.text.value;
// Insert a task into the collection
Tasks.insert({
text: text,
createdAt: new Date() // current time
});
// Clear form
event.target.text.value = "";
},
"submit .delete-task": function (event) {
// Prevent default browser form submit
event.preventDefault();
// Get value from form element
var text = event.target.text.value;
// Insert a task into the collection
Tasks.remove({
text: text,
});
// Clear form
event.target.text.value = "";
}
});
}
The new-task form works fine, but the delete-task form doesn't work. I tried a similar query using shell (meteor mongo) and it worked. What error do I have here?
EDIT:
Here's the html as well:
<head>
<title>Todo List</title>
</head>
<body>
<div class="container">
<header>
<h1>Todo List</h1>
<form class="new-task">
<h2> Add a task </h2>
<input type="text" name="text" placeholder="Type to add new tasks" />
</form>
<form class="delete-task">
<h2> Delete a task </h2>
<input type="text" name="text" placeholder="Type to delete tasks" />
</form>
</header>
<ul>
{{#each tasks}}
{{> task}}
{{/each}}
</ul>
</div>
</body>
<template name="task">
<li class="{{#if checked}}checked{{/if}}">
<button class="delete">×</button>
<input type="checkbox" checked="{{checked}}" class="toggle-checked" />
<span class="text">{{text}}</span>
</li>
</template>
Uncaught Error: Not permitted. Untrusted code may only remove documents by ID. [403]
This shows up in the browser's javascript console when you try to run the deletion by text as you've described in your code / problem statement. This was a design decision by the Meteor team in 0.5.8 and is discussed in this previous question.
You can have this functionality if you create a server side method. Otherwise your client side code will have to delete by ID. Something like this:
Change your Tasks.remove({text: text}) call to Meteor.call('removeTaskByText', text) on the client code, and on the server side define:
Meteor.methods({
'removeTaskByText': function(text){
Tasks.remove({text: text});
}
});

Div inside of anchor, stop redirect

I have next html:
<a href="https://google.com" >
<div id="first"></div>
<div id="second"></div>
</a>
Currently when I click to div #first it takes me to https://google.com.I don't want it. I want to not have effect anchor on div #first, so when I click on div #first nothing is happen.
And I cannot handle anchor, let say that I can add javascript just for div #first.
EDIT
I forgot to tell that my div contain form with attached event submit:
<script>
function submitForm(_this){
//do Ajax call
return false;
}
</script>
<a href="https://google.com" >
<div id="first"></div>
<form method="post" onsubmit="return submitForm(this)">
<input id="email" name="Email" type="text">
<input id="submit" name="submit" value="Register" type="submit">
<form>
<div id="second"></div>
</a>
So if I add this:
<script>
jQuery("#first").on("click", function (e) { e.preventDefault(); });
</script>
Then my form doesn't work.
EDIT
So if add e.stopPropagation() on input submit click, like this
<script>
jQuery("#submit").on("click", function (e) { e.stopPropagation(); });
jQuery("#first").on("click", function (e) { e.preventDefault(); });
</script>
It will work fine, but e.stopPropagation(); doesn't work on fine in Safari. In Safari when I click on input submit it still leads me to the anchor link.
cancel the click with preventDefault
$("#firs").on("click", function (e) { e.preventDefault(); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="https://example.com" >
<div id="firs">X</div>
<div id="second">Y</div>
</a>
Either dont't put the div in the anchor, or use the following:
document.getElementById('firs').addEventListener('click', function(event) {
event.preventDefault();
});
I think that this might help (your id says firs but sake of spelling I'll put first)
$("#first *").attr("disabled", "disabled").off('click');
use the following
event.preventDefault()

Javascript/jQuery watch for CSS Changes

I have a simple dropdown that opens up a search field when you click it. Even though I have the text field of this search set to autofocus, it's not working for all browsers.
What method of Javascript/jQuery would I use to check if the containing UL css display is set to block, so that I can force the focus to be on the field using .focus().
HTML:
Quick Search
<ul class="dropdown-menu" role="menu">
<li id="li-quicksearch">
<form id="mainSearch" class="form-search">
<p>
<input type="text" id="inputSearch" class="form-control" placeholder="Quick Search" required="" autofocus autocomplete="off">
<button type="submit">SUBMIT</button>
</p>
</form>
</li>
</ul>
EDIT: There is no css change event so you'll have to approach the problem in 1 of 2 ways.
check the dom element in set intervals to see if its css has changed
trigger an event when the css of the dom element is changed by user interaction/your code.
the first way will look something like this:
var element = $(".dropdown-menu");
function checkForChanges()
{
if (element.css('display') == 'block')
{
// do your .focus() stuff here
}
setTimeout(checkForChanges, 500); // does this every half second.
}
or the second way:
$('.toggle').on('click', function() {
$('.dropdown-menu').toggle();
$('.dropdown-menu').trigger('change');
});
$('.dropdown-menu').on('change', function(){
if($(this).css(.css('display') == 'block')
{
// do your .focus() stuff here
}
});
You can check the display value of the ul using pure JavaScript with this:
JS:
var display = document.getElementById('dropdown-menu')[0].style.display;
if (display === 'block') {
//do what you want.
}
Or using jQuery:
if ($('.dropdown-menu').css('display') === 'block') {
//do what you want.
}
It looks like you are using bootstrap to create the dropdown. If that is the case you can use the "shown" event. However you need to attach the event on a container element.
Html
<div class="quickSearchContainer">
Quick Search
<ul class="dropdown-menu" role="menu">
<li id="li-quicksearch">
<form id="mainSearch" class="form-search">
<p>
<input type="text" id="inputSearch" class="form-control" placeholder="Quick Search" required="" autofocus autocomplete="off">
<button type="submit">SUBMIT</button>
</p>
</form>
</li>
</ul>
</div>
Javascript
$('#quickSearchContainer').on('show.bs.dropdown', function () {
$('#inputSearch').focus();
});
I want to thank everyone for their input, but the working solution that I found was to modify the bootstrap JS to allow for an autofocus on toggleClass of the OPEN for the dropdowns. Everyone gets kudos!

How to trigger onclick by pressing enter using inline javascript?

[FYI: i am not allowed to change how it was marked up. div will be clicked.. not a button or anchor]
i have a menu(that should pass on accessibility standards) that will open its submenu when clicked.
this is the onclick function, and i need to do the same function when pressing enter key,
// parent menu (this will repeat)
<div onclick="javascript:ToggleMenu('Calendar');" class="menu-item" style="cursor: hand;" tabindex="2">
<p>Calendar</p>
</div>
//submenu (this will repeat)
<div id="Calendar" class="menu-subitem" style="display: none;" tabindex="2">
<a onclick="Audit(this)" tabindex="2" href="Calendar/CalendarAssignment.aspx" id="TM_C1">Calendar Assignment</a>
<a onclick="Audit(this)" tabindex="2" href="Calendar/ShiftAssignment.aspx" id="TM_C2">Shift Assignment</a>
</div>
thanks!
i tried my best to be clear whew!
Here's the accessible solution while keeping a div:
<div id="foo" role="button" tabindex="0">Toggle menu</div>
<script>
$('#foo').click(function() {
ToggleMenu('<%# Container.DataItem.FuncID %>');
}).keydown(function(e) {
if (e.which === 32 || e.which === 13) {
this.click();
}
});
</script>
But honestly you should just use a button:
<button id="foo">Toggle menu</button>
<script>
$('#foo').click(function() {
ToggleMenu('<%# Container.DataItem.FuncID %>');
});
</script>
This will do it when they hit the enter key anywhere on the page
<div onclick="javascript:ToggleMenu('<%# Container.DataItem.FuncID %>');">
<script>
document.addEventListener("keypress", function (evt)
{
if (evt.keyCode === 13) {
//they pressed enter
//now get the divevent
var div = document.querySelector('div[onclick*="ToggleMenu"]');
//trigger the event
div.onclick.apply(div);
}
}
);
</script>
I can see you have an error in your code
onclick"javascript:xxxx"
is not correct,
"javascript:xxx"
should using on "a" tag "href" attribute, just remove the "javascript:" in your onclick attribute and you may get what you want.

Redirect page depending on form submission in Jquery/Javascript?

I'm working on a page that should redirect depending on what the user enters in the form, and I can't seem to figure it out. New to Javascript, and eager to learn!
Here is the html:
<body>
<div id="header">
<div id="navcontainer">
<ul>
<li> Home </li>
<li> Scents </li>
<li> About </li>
<li> Contact </li>
</ul>
</div>
</div>
<div id="content">
<p>Hi, how are you feeling today?</p>
<form> <input id="feels" type="text" name="feeling" size="35" onchange="checkfeels(#feels.value);">
<input type="submit" value="submit" >
</form>
</div>
And the Javascript I have so far:
function checkfeels(myFeels) {
switch (myFeels)
{
case "good":
document.location.href = 'scents.html';
break
case "bad":
alert(2);
document.location.href = 'scents2.html';
default:
alert("whatever");
}
}
Any help is really appreciated, thanks!
Put the
return checkfeels(this.elements.feeling.value)
in the form onsubmit attribute.
"feeling" in current case is the name of input field. <input type="text" name="feeling" > in your code.
And add
return false;
to the end of the checkfeels function to prevent default action (submiting form to server).
Also, you can pass to function whole form, for example:
return checkfeels(this)
And work already with whole form in checkfeels function.
function checkfeels(form) {
var feeling = form.elements.feeling.value;
var otherField = form.elements.otherField.value;
// code with your logic here
return false; // prevent default action
}
Put the following code:
checkfeels($('#feels').val());
return false;
in the form onsubmit attribute.
You cannot get what the user types with #feels.value (it seems that you make a mistake between jQuery syntax and javascript).
You can do that in pure javascript :
function checkfeels() {
var myFeels = document.getElementById('feels').value;
switch (myFeels) {
case "good":
document.location.href = 'scents.html';
break
case "bad":
alert(2);
document.location.href = 'scents2.html';
default:
alert("whatever");
}
}
You get what the user type with : document.getElementById('feels').value and you don't need to give any parameters to the function.
If you use jQuery, you can get the value with : $('#feels').val();

Categories