Jquery stop repeat my code with after? - javascript

I have a problem with my input and my Jquery :
Basically I have this code :
HTML:
<form id="formUser">
<div class="row">
<div class="small-8">
<div class="row">
<div class="small-6 columns">
<label for="right-label" class="right inline">First name</label>
</div>
<div class="small-6 columns">
<input type="text" name="fisrtName" placeholder="First name">
</div>
</div>
</div>
</div>
<div class="row text-center">
<input type="checkbox" class="check"><label for="checkbox"><p>I accept the review agreement</p></label>
<button type="submit" class="button join">Let's Go !</button>
</div>
</form>
JS :
<script type="text/javascript">
$(function(){
$("#formUser").submit(function(){
if(!$('input[name="fisrtName"]').val()) {
$('input[name="fisrtName"]').addClass("error");
$('input[name="fisrtName"]').after("<small class='error'>Invalid entry</small>");
}
return false;
});
});
</script>
And I have this
When I click several time on the button... the error class is repeat ..
How can i stop the repeat or incrase the actual class error ?

Maybe you should be doing something like this
$("#formUser").submit(function(){
var $element = $('internal[name="fisrtName]');
// ^ save this much faster ^
// ^ you have spelt firstName wrong also ^
// check val and check next element isn't error
if($element.val() && $element.next().hasClass('error') === false) {
$element.addClass('error').after("<small class='error'>Invalid entry</small>");
} else {
// now remove it if you need to
}
return false;
});
Hope it helps.
You should always cache your elements
By doing this:
$('internal[name="fisrtName');
$('internal[name="fisrtName');
$('internal[name="fisrtName');
You're calling the jQuery function 3 times when you do not need to.

You can use:
if($('input[name="fisrtName"]').find('.error').length==0)
$('input[name="fisrtName"]').after("<small class='error'>Invalid entry</small>");

Or:
var $firstName = $('input[name="fisrtName"]');
if (!$firstName.hasClass("error")) {
$firstName.addClass("error");
$firstName.after("<small class='error'/>");
}
$firstName.find("small.error").text("Invalid entry");

Try to change your code with this, I have aded the line "$('small.error').remove();"
$.q("#formUser").submit(function(){
if(!$.q('input[name="fisrtName"]').val()) {
$.q('small.error').remove();
$.q('input[name="fisrtName"]').addClass("error");
$.q('input[name="fisrtName"]').after("<small class='error'>Invalid entry</small>");
}
return false;
});

Related

Select a button by its value and click on it

How can I select a button based on its value and click on it (in Javascript)?
I already found it in JQuery:
$('input [type = button] [value = my task]');
My HTML Code for the Button is :
<button type="submit" value="My Task" id="button5b9f66b97cf47" class="green ">
<div class="button-container addHoverClick">
<div class="button-background">
<div class="buttonStart">
<div class="buttonEnd">
<div class="buttonMiddle"></div>
</div>
</div>
</div>
<div class="button-content">Lancer le pillage</div>
</div>
<script type="text/javascript" id="button5b9f66b97cf47_script">
jQuery(function() {
jQuery('button#button5b9f66b97cf47').click(function () {
jQuery(window).trigger('buttonClicked', [this, {"type":"submit","value":"My Task","name":"","id":"button5b9f66b97cf47","class":"green ","title":"","confirm":"","onclick":""}]);
});
});
</script>
What is the equivalent in JS and how may i click on it
(probably like this: buttonSelected.click(); ) .
And how do i run the javascript of the button clicked ?
Use querySelector to select it. Then click()
Your HTML has a button and not an input element so I changed the selector to match the HTML.
let button = document.querySelector('button[value="my task"]');
button.click();
<button type="submit" value="my task" id="button5b9f54e9ec4ad" class="green " onclick="alert('clicked')">
<div class="button-container addHoverClick">
<div class="button-background">
<div class="buttonStart">
<div class="buttonEnd">
<div class="buttonMiddle"></div>
</div>
</div>
</div>
<div class="button-content">Launch</div>
</div>
</button>
Otherwise, use this selector:
document.querySelector('input[type="button"][value="my task"]')
Note that if you have multiple buttons with the same value you'll need to use querySelectorAll and you'll get a list of all the buttons.
Then you can loop over them and click() them all.
Edit - new snippet after question edit
jQuery(function() {
jQuery('button#button5b9f66b97cf47').click(function() {alert('success')});
document.querySelector('button[value="My Task"]').click();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="submit" value="My Task" id="button5b9f66b97cf47" class="green ">
<div class="button-container addHoverClick">
<div class="button-background">
<div class="buttonStart">
<div class="buttonEnd">
<div class="buttonMiddle"></div>
</div>
</div>
</div>
<div class="button-content">Lancer le pillage</div>
</div>
you can try:
var elements = document.querySelectorAll("input[type = button][value=something]");
note that querySelectorAll returns array so to get the element you should use indexing to index the first element of the returned array and then to click:
elements[0].click()
and to add a event listener u can do:
elements[0].addEventListener('click', function(event){
event.preventDefault()
//do anything after button is clicked
})
and don't forget to add onclick attribute to your button element in html to call the equivalent function in your javascript code with event object
I am not recommended this way because of excess your coding but as you mentioned, below are the equivalent way.
$(document).ready(function() {
var selectedbuttonValue = "2"; //change value here to find that button
var buttonList = document.getElementsByClassName("btn")
for (i = 0; i < buttonList.length; i++) {
var currentButtonValue = buttonList[i];
if (selectedbuttonValue == currentButtonValue.value) {
currentButtonValue.click();
}
}
});
function callMe(valuee) {
alert(valuee);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<input type="button" class="btn" value="1" onclick="callMe(1)" />
<input type="button" class="btn" value="2" onclick="callMe(2)" />
<input type="button" class="btn" value="3" onclick="callMe(3)" />
Using JavaScripts querySelector in similiar manner works in this case
document.querySelector('input[type="button"][value="my task" i]')
EDIT
You might save your selection in variable and attach eventListener to it. This would work as you desire.
Notice event.preventDefault() -function, if this would be part of form it would example prevent default from send action and you should trigger sending form manually. event-variable itselfs contains object about your click-event
var button = document.querySelector('input[type="button"][value="my task" i]')
button.addEventListener('click', function(event){
event.preventDefault() // Example if you want to prevent button default behaviour
// RUN YOUR CODE =>
console.log(123)
})

jQuery find() & each() on dynamic elements

I've got a <div> element that contains multiple other <div>'s that are populated dynamically using jQuery/Ajax, I'm trying to run the following code but find() fails to get any of them.
Here's my HTML boilerplate prior to my data being populated.
<input type="text" id="inv-filter" class="form-control">
<div class="row itemList" style="margin-right: -2px;margin-left:-2px;">
</div>
And here's what it looks like after population.
<input type="text" id="inv-filter" class="form-control">
<div class="row itemList" style="margin-right: -2px;margin-left:-2px;">
<div class="col-xs-3 col-sm-2 shop-item" data-hash="Item Name 1">
</div>
<div class="col-xs-3 col-sm-2 shop-item" data-hash="Item Name 2">
</div>
......
</div>
My Javascript looks like the following:
$('#inv-filter').keyup(function() {
var search = $(this).val().toLowerCase();
var $sellContainer = $('.itemList');
if (search.trim() === '') {
$sellContainer.find('.shop-item').show();
$sellContainer.find('.shop-item.selected').hide();
return;
}
$sellContainer.find('.sell-item').each(function() {
if (!$(this).hasClass('selected') && $(this).data('hash').text().toLowerCase().includes(search)) {
$(this).show();
} else {
$(this).hide();
}
});
});
I've ran multiple tests inside console debugger such as $('.itemList').length() etc.. but doesn't appear to find any results & when entering text into my input field, nothing is happening
$sellContainer.find('.sell-item').each(function() { //replace sell-item with shop-item
if (!$(this).hasClass('selected') && $(this).data('hash').text().toLowerCase().includes(search)) {
$(this).show();
} else {
$(this).hide();
}
});

POST request doesn't recognize in my controller using Opencart

I have a problem in my code. In my setup I created a single page for language selection. And I copy some of opencart's code on language template and also on controller. But my problem is after passing my form, the action controller doesn't get any POST data from my form.
<form action="{{ action }}" method="POST" enctype="multipart/form-data" id="form-language">
<div class="col-lg-4">
<div class="border_index_in">
<div class="holder">
<h3>ENGLISH</h3>
<button class="language-select btn btn-green" type="button" name="en-gb">Choose</button>
</div>
</div>
</div>
<div class="col-lg-4">
<div class="border_index_in">
<div class="holder">
<h3>日本語</h3>
<button class="language-select btn btn-green" type="button" name="jap">選択</button>
</div>
</div>
</div>
<div class="col-lg-4">
<div class="border_index_in">
<div class="holder">
<h3>中文</h3>
<button class="language-select btn btn-green" type="button" name="zh-hk">选择</button>
</div>
</div>
</div>
</form>
JS:
// Language
$('#form-language .language-select').on('click', function(e) {
e.preventDefault();
$('#form-language input[name=\'code\']').val($(this).attr('name'));
$('#form-language').submit();
});
Controller to show my language selection page
public function language_switch() {
$this->load->model('setting/extension');
$this->document->setTitle($this->config->get('config_meta_title'));
$this->document->setDescription($this->config->get('config_meta_description'));
$this->document->setKeywords($this->config->get('config_meta_keyword'));
if (isset($this->request->get['route'])) {
$this->document->addLink($this->config->get('config_url'), 'canonical');
}
$data['action'] = $this->url->link('common/language/language');
$data['code'] = $this->session->data['language'];
$styles_array = array(
'catalog/view/theme/onemidorie/stylesheet/style.css'
);
$scripts_array = array(
);
foreach($styles_array as $st) {
$this->document->addStyle($st);
}
foreach($scripts_array as $sc) {
$this->document->addScript($sc);
}
$data['styles'] = $this->document->getStyles();
$data['scripts'] = $this->document->getScripts();
$data['footer'] = $this->load->controller('common/footer');
$data['header'] = $this->load->controller('common/header');
$this->response->setOutput($this->load->view('common/language_selection', $data));
}
Controller that should accept the POST data from my form:
public function language() {
print_r($this->request->post['code']); //Notice: Undefined index: code
die;
if (isset($this->request->post['code'])) {
$this->session->data['language'] = $this->request->post['code'];
}
if (isset($this->request->post['redirect'])) {
$this->response->redirect($this->request->post['redirect']);
} else {
$this->response->redirect($this->url->link('common/home'));
}
}
Can you help me this?
You should use
print_r($this->request->post);
die;
Then you will get some post data.
because you define the name like "en-gb","jap" and "zh-hk". So please use above code then you can get solution.
You're not posting any data - you're just showing a button. Use something more like
<input type="submit" value="english" name="lang"/>
<input type="submit" value="japanese" name="lang"/>
etc. then just look at
$_POST['lang']
and see if it's english, japanese or whatever.
You can find out how opencart set language in /catalog/controller/startup/startup.php:
// Overwrite the default language object
$language = new Language($code);
$language->load($code);
$this->registry->set('language', $language);
So in controller what should accept the POST data you should dublicate this code before loading language:
// $this->request->post['code'] = 'en-gb' or 'ru-ru' or whatever.
$language = new Language($this->request->post['code']);
$language->load($this->request->post['code']);
$this->registry->set('language', $language);
// now opencart use new language and you can use it too:
$this->load->language('common/header');
$text_home = $this->language->get('text_home');
This works for me in opencart 2

Why isn't meteor injecting the text from my template helpers?

Im trying to dynamically generate a table of two different sets of data. My database isnt empty and the returns have been verified as well. but when i check the rendered page the corresponding html isnt there as if nothing as returned.
template/html:
<template name="room">
<div class="container-fluid">
<h1> Sprint Retrospective</h1>
<hr>
<div class="input-group">
<input type="text" class="form-control thoughts" placeholder="Thoughts..." aria-describedby="basic-addon1">
<span class="input-group-addon">
<input id="wentWell" type="checkbox" aria-label="..."> Went Well
</span>
<span class="input-group-addon">
<input id="wentWrong" type="checkbox" aria-label="..."> Went Wrong
</span>
<span class="input-group-btn">
<button class="btn btn-default" type="button">Submit!</button>
</span>
</div>
<hr>
{{#if haveCards}}
<div class="container-fluid">
<div class="row">
<div class="col-xs-6 col-sm-6">
<div class="row">Went Well</div>
{{#each wentWell}}
{{>card}}
{{/each}}
</div>
<div class="col-xs-6 col-sm-6">
<div class="row">Went Wrong</div>
{{#each wentWrong}}
{{>card}}
{{/each}}
</div>
</div>
</div>
{{/if}}
</div>
</template>
Javascript:
"use strict";
/**
*
**/
var Cards = new Mongo.Collection('cards');
var allCards;
var wentWellCards;
var wentWrongCards;
if(Meteor.isClient){
Tracker.autorun(function(){
allCards = Cards.find({},{sort:{createdAt:-1}});
wentWellCards = Cards.find({category:"Went Well"},{sort:{createdAt:-1}});
wentWrongCards = Cards.find({category:"Went Wrong"},{sort:{createdAt:-1}});
});
Template.room.helpers({
haveCards: function(){
if(allCards != null && allCards != undefined && allCards.length > 0)
return true;
return false;
},
wentWell: function(){
return this.wentWellCards;
},
wentWrong: function(){
return this.wentWrongCards;
}
});
}
Jeremy answer its actually more in point, but..
Lets try to fix that code a little bit.
Lets change the wentWell and wentWrong helpers to look more clean like this.
wentWell: function(){
return Cards.find({category:"Went Well"},{sort:{createdAt:-1}});
},
wentWrong: function(){
return Cards.find({category:"Went Wrong"},{sort:{createdAt:-1}});
}
Also for the haveCards helpers you can do something like
haveCards: function(){
return Cards.find().count() >= 1 //for example or return just findOne()
}
Your helpers should return wentWellCards instead of this.wentWellCards, etc.
Your helpers are not reactive, so, when the data is loaded (which happens after the page is rendered) the helpers are not re-run.
Simply, call the reactive methods (the minimongo queries) in the helper directly. This will get them re-run once the data is available
Also, when you check the count, you need to fetch the collection
Cards = new Mongo.Collection('cards');
if(Meteor.isServer){
Meteor.publish('cards', function() {
return Cards.find({},{sort:{createdAt:-1}});
});
}
if(Meteor.isClient){
Template.room.onCreated(function(){
this.subscribe('cards');
});
Template.room.helpers({
haveCards: function(){
var allCards = Cards.find({},{sort:{createdAt:-1}}).fetch();
return (allCards != null && allCards != undefined && allCards.length > 0);
},
wentWell: function(){
return wentWellCards = Cards.find({category:"Went Well"},{sort:{createdAt:-1}});
},
wentWrong: function(){
return wentWrongCards = Cards.find({category:"Went Wrong"},{sort:{createdAt:-1}});
}
});
}
And you will need to publish the collection from the server and subscribe from the template (unless you are using autopublish)

Return key not working on input text tag

I have the following code
<div class="framepage">
<header>
<script type="text/javascript">
function getBaseUrl() {
return "#Url.Content("~/paging")";
}
function LocationSearch(baseUrl) {
window.location = getBaseUrl() + "/LocationSearch?searchstring=" + (document.getElementById('vestigingen').value);
}
</script>
</div>
</div>
</div>
</header>
<section id="maintest">
<ul id="menu">
<li>
<form class="navbar-search">
<div class="icon-search icon-white"></div>
<input type="text" class="search-query span3" id="vestigingen">
</form>
<input type="button" class="buttonzz" value="zoeken" onclick="LocationSearch()"/>
</li>
<li>Lijst</li>
<li>Lijst</li>
</ul>
<div class="fence">
#RenderBody()
</div>
My problem concerns the return key. Whenever I press the return key my inserted value in the input( type=text) tag is lost.
For instance I type New York and want to get result in NY , my field is empty.
If I type it in and use my submit button everything is fine. Can anyone help me here?
You don't need any javascript for this. Simply use HTML helpers to generate your search form:
#using (Html.BeginForm("LocationSearch", "SomeController", FormMethod.Get, new { #class = "navbar-search" }))
{
<div class="icon-search icon-white"></div>
#Html.TextBox("searchstring")
<input type="submit" value="Search" />
}
You could change the type to submit rather than button and this will set the button to default.
Return key submits your form and in your case your page will refresh. Try to prevent this default action. There are plenty of tricks for that!

Categories

Resources