need help about settimeout() jquery - jquery-selectors

Here is my html. I want to show specific paragraph when I'll select different option. also want to show a loader before showing each paragraph. suppose when I'll select Algeria from the select it should be show first loader, after few second the loader should hide and show the specific paragraph which contain the id="algeria".
<select id="oh-select">
<option value="algeria">Algeria</option>
<option value="australia">Australia</option>
<option value="brazil">Brazil</option>
<option value="brunei">Brunei</option>
<option value="cameroon">Cameroon</option>
<option value="canada">Canada</option>
</select>
<div id="oi-loader"> Loading</div>
<p class="nothing" id="algeria">Algeria</p>
<p class="nothing" id="australia">Australia</p>
<p class="nothing" id="brazil">Brazil</p>
<p class="nothing" id="brunei">Brunei</p>
<p class="nothing" id="cameroon">Cameroon</p>
<p class="nothing" id="canada">Canada</p>
The problem is if want to show paragraph using setTimeout() after few second on change it's not working.but without setTimeout() it's working partially. Here is jquery what I wrote:
$(document).ready(function(){
$("#oi-loader").hide();
$('.nothing').hide();
$('#oh-select').change(function() {
$('.nothing').hide();
$("#oi-loader").show();
setTimeout(function() {
$("#oi-loader").hide();
}, 3000);
setTimeout(function() {
$("#" + $(this).val()).show();
}, 4000);
});
});

Assign $(this).val() to a variable to avoid the change of its value by changing its functional context.
$(document).ready(function(){
$("#oi-loader").hide();
$('.nothing').hide();
$('#oh-select').change(function() {
// assigning this to a variable
var a = $(this).val()
$('.nothing').hide();
$("#oi-loader").show();
setTimeout(function() {
$("#oi-loader").hide();
}, 3000);
setTimeout(function() {
// using variable
$("#" + a).show();
}, 4000);
});
});

Don't need to use setTimeout() function twice, you can write this code like:
$(document).ready(function(){
$("#oi-loader").hide();
$('.nothing').hide();
$('#oh-select').change(function() {
var curEle = $(this).val();
$("#oi-loader").show();
$('.nothing').hide();
setTimeout(function() {
$("#" + curEle).show();
$("#oi-loader").hide();
}, 4000);
});
});

Related

MeteorJS form submission is refreshing the page with event.preventDefault() enabled

The dating application is built with MeteorJS and the page refreshes whenever I attempt to submit this form to register a user. Also, Meteor.user().services.twitter.profile_image_url doesn't seem to get Twitter image. Please help
imports/ui/components/partials/register-user.html
<template name="registerUser">
<div class="user-card">
<form id="user-form">
<div class="row">
<label for="gender">gender</label>
<select id="gender">
<option value="cis man">cis man</option>
<option value="cis woman">cis woman</option>
<option value="non binary" selected>non binary</option>
<option value="trans man">trans man</option>
<option value="trans woman">trans woman</option>
</select>
</div>
<div class="row">
<label for="prefer">seeking</label>
<select id="prefer">
<option value="cis men">cis men</option>
<option value="cis women">cis women</option>
<option value="everyone" selected>everyone</option>
<option value="non binary">non binary</option>
<option value="trans women">trans women</option>
<option value="trans men">trans men</option>
</select>
</div>
<div class="row">
<button class="button-primary register-user" type="submit" form="user-form">register</button>
</div>
</form>
</div>
</template>
imports/ui/components/partials/register-user.js
import { Meteor } from 'meteor/meteor';
import { Session } from 'meteor/session';
import './register-user.html';
Template.registerUser.onCreated(function () {
this.register_name = Meteor.user().profile.name;
this.register_img = Meteor.user().services.twitter.profile_image_url;
});
Template.registerUser.events({
'submit .register-user' (event) {
event.preventDefault();
var gender = event.target.gender.value;
var prefer = event.target.prefer.value;
if (confirm("by continuing you verify you are a minimum of 21 years old")) {
Meteor.call('register.user', this.register_name, "", gender, prefer, (error) => {
if (error) {
Flash.danger(error.error, 3000);
} else {
Session.set({'complete': true});
}
});
}
},
});
imports/api/methods.js
...
'register.user': function(name, img, gender, prefer) {
RegisteredUsers.insert({ _id: this.userId, complete: true, role: false });
Profiles.insert({
_id: this.userId, name: name, img: img, gender: gender, prefer: prefer, address: "", right: [], matches: [],
});
// redisCollection.hset(this.userId, { "name": name, "img": img, "gender": gender });
},
...
Your example show an error on event mapping:
'submit .register-user' (event) {
You used a class mapping of the button, but the submit event is from the form. Then change it to:
'submit #user-form' (event) {
I think that the issue is because you are mapping the submit event to the button which has the class register-user. Try changing your code to refer to the form from which the submit event comes. You can use its id (user-form) for doing that.
It'd be something like this:
'submit #user-form'(event) {
event.preventDefault();
...
}

getting data from external json url in yii2 framework

i have to get data from externaljson url api in yii2 framework,json url is:https://next.json-generator.com/api/json/get/EympRaB4D
<p>
<input type="button" value="Fill SELECT Dropdown List with JSON" id="bt" />
</p>
<select id="sel">
<option value="">-- Select --</option>
</select>
<p id="msg"></p>
<script>
$(document).ready(function () {
$('#bt').click(function () {
var url = "https://next.json-generator.com/api/json/get/EympRaB4D";
$.getJSON(url, function (data) {
$.each(data, function (index, value) {
// APPEND OR INSERT DATA TO SELECT ELEMENT.
$('#sel').append('<option value="' + value.company + '">' + value.country + '</option>');
});
});
});
// SHOW SELECTED VALUE.
$('#sel').change(function () {
$('#msg').text('Selected Item: ' + this.options[this.selectedIndex].text);
});
});
$(document).ready(function () {
$('#bt').click(function () {
$.ajax({
url: "https://next.json-generator.com/api/json/get/EympRaB4D",
type: "GET",
success: function (result) {
//console.log(result);
for(var dataSet in result){
$("#sel").append("<option value="+result[dataSet].company+">"+result[dataSet].country+"</option>");
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log(errorThrown);
}
});
});
// SHOW SELECTED VALUE.
$('#sel').change(function () {
$('#msg').text('Selected Item: ' + this.options[this.selectedIndex].text);
});
});
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<p>
<input type="button" value="Fill SELECT Dropdown List with JSON" id="bt" />
</p>
<select id="sel">
<option value="">-- Select --</option>
</select>
<label id="msg"></label>
</body>
</html>

Meteor + React: Append response to DOM after a Meteor.call?

I am super new to React and quite new to Meteor.
I am doing a Meteor.call to a function ('getTheThing'). That function is fetching some information and returns the information as a response. In my browser I can see that the method is returning the correct information (a string), but how do I get that response into the DOM?
(As you can see, I have tried to place it in the DOM with the use of ReactDOM.findDOMNode(this.refs.result).html(response);, but then I get this error in my console: Exception in delivering result of invoking 'getTheThing': TypeError: Cannot read property 'result' of undefined)
App = React.createClass({
findTheThing(event) {
event.preventDefault();
var username = ReactDOM.findDOMNode(this.refs.textInput).value.trim();
Meteor.call("getTheThing", username, function(error, response){
console.log(response);
ReactDOM.findDOMNode(this.refs.result).html(response);
});
ReactDOM.findDOMNode(this.refs.textInput).value = "";
},
render(){
return(
<div className="row">
<div className="col-xs-12">
<div className="landing-container">
<form className="username" onSubmit={this.findTheThing} >
<input
type="text"
ref="textInput"
placeholder="what's your username?"
/>
</form>
</div>
<div ref="result">
</div>
</div>
</div>
);
}
});
this is under the different context, thus does not contain the refs there. Also, you cannot set html for the Dom Element. You need to change into Jquery element
var _this = this;
Meteor.call("getTheThing", username, function(error, response){
console.log(response);
$(ReactDOM.findDOMNode(_this.refs.result)).html(response);
});
Though i recommend you to set the response into the state and let the component re-rendered
For a complete React way
App = React.createClass({
getInitialState() {
return { result: "" };
},
shouldComponentUpdate (nextProps: any, nextState: any): boolean {
return (nextState['result'] !== this.state['result']);
},
findTheThing(event) {
event.preventDefault();
var username = ReactDOM.findDOMNode(this.refs.textInput).value.trim();
Meteor.call("getTheThing", username, function(error, response){
console.log(response);
_this.setState({ result: response });
});
ReactDOM.findDOMNode(this.refs.textInput).value = "";
},
render(){
return(
<div className="row">
<div className="col-xs-12">
<div className="landing-container">
<form className="username" onSubmit={this.findTheThing} >
<input
type="text"
ref="textInput"
placeholder="what's your username?"
/>
</form>
</div>
<div ref="result">{this.state['result']}</div>
</div>
</div>
</div>
);
}
});

meteor template.dynamic load data from session

i have a page split in two:
on left {{> expenseList }}
on right {{> Template.dynamic template="expenseForm" data=expenseData}}
on left its a list
on right its a form to enter elements in the list.
desired behaviour:
1: form is empty and ready to add expenses
2: add an expense, form is cleared and ready for next
3: if i click on the left on the submitted expense from {{> expenseList }} the form is populated with the data of that expense and i can update that entry.
i cannot get it to work though. my form doesn't dynamically change the data. i tried to simplify code and add it below
the page code:
<template name="claimsPage">
<div class="wrapper wrapper-content animated fadeInRight">
<div class="row">
<div class="col-md-4">
{{> expenseList }}
</div>
{{> Template.dynamic template="expenseForm" data=expenseData}}
</div>
</div>
</template>
the page js
Template.claimsPage.helpers({
expenseData: function() {
var data = Session.get('expenseData');
return data;
}
});
the list js
Template.expenseList.events({
'click a': function(e) {
e.preventDefault();
var data = {
date: this.date,
description: this.description,
_id: this._id
};
Session.set('expenseData', data);
}
});
the form js
Template.expenseForm.helpers({
purposes: function() {
return Purposes.find();
},
expenseData: function(){
return Session.get('expenseData')
}
});
Template.expenseForm.events({
'click #add-expense': function(e){
e.preventDefault();
var template = Template.instance();
var expense = {
date: template.find("[name='date']" ).value,
description: template.find("[name='description']" ).value,
purposeName: template.find("[name='purpose'] option:selected" ).value,
_id: Random.id()
};
Meteor.call('addExpense', expense, function(error, result) {
if (error)
return alert(error.reason);
template.find("form").reset();
});
}
});
the form html
<template name="expenseForm">
<form>
<input name="date" type="text" value="">
<input name="description" type="text" value="">
<select name="purpose">
<option value="">Select a purpose</option>
{{#each purposes}}
<option value="{{this.purposeName}}">{{this.purposeName}}</option>
{{/each}}
</select>
<button id="add-expense" type="button">Submit</button>
</form>
</template>
I would really appreciate your help with this,
Thanks,
Cezar

Error submitting form data using knockout and mvc

#model NewDemoApp.Models.DemoViewModel
#{
ViewBag.Title = "Home Page";
}
#*<script src="#Url.Content("~/Scripts/jquery-1.9.1.min.js")" type="text/javascript"></script>*#
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script src="#Url.Content("~/Scripts/knockout-3.3.0.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script type="text/javascript">
var viewModel;
var compViewModel, userViewModel;
$(document).ready(function () {
$(".wizard-step:visible").hide();
$(".wizard-step:first").show(); // show first step
$("#back-step").hide();
var result = #Html.Raw(Json.Encode(Model));
var viewModel = new DemoViewModel(result.userViewModel);
//viewModel.userViewModel.FirstName = result.userViewModel.FirstName;
//viewModel.userViewModel.LastName = result.userViewModel.LastName;
//viewModel.userViewModel.State = result.userViewModel.State;
//viewModel.userViewModel.City = result.userViewModel.City;
ko.applyBindings(viewModel);
});
var userVM = function(){
FirstName = ko.observable(),
LastName = ko.observable(),
State = ko.observable(),
City = ko.observable()
};
function DemoViewModel(data) {
var self = this;
self.userViewModel = function UserViewModel(data) {
userVM.FirstName = data.FirstName;
userVM.LastName = data.LastName;
userVM.State = data.State;
userVM.City = data.City;
}
self.Next = function () {
var $step = $(".wizard-step:visible"); // get current step
var form = $("#myFrm");
var validator = $("#myFrm").validate(); // obtain validator
var anyError = false;
$step.find("input").each(function () {
if (!validator.element(this)) { // validate every input element inside this step
anyError = true;
}
});
if (anyError)
return false; // exit if any error found
if ($step.next().hasClass("confirm")) { // is it confirmation?
$step.hide().prev(); // hide the current step
$step.next().show(); // show the next step
$("#back-step").show();
$("#next-step").hide();
//$("#myFrm").submit();
// show confirmation asynchronously
//$.post("/wizard/confirm", $("#myFrm").serialize(), function (r) {
// // inject response in confirmation step
// $(".wizard-step.confirm").html(r);
//});
}
else {
if ($step.next().hasClass("wizard-step")) { // is there any next step?
$step.hide().next().fadeIn(); // show it and hide current step
$("#back-step").show(); // recall to show backStep button
$("#next-step").show();
}
}
}
self.Back = function () {
var $step = $(".wizard-step:visible"); // get current step
if ($step.prev().hasClass("wizard-step")) { // is there any previous step?
$step.hide().prev().fadeIn(); // show it and hide current step
// disable backstep button?
if (!$step.prev().prev().hasClass("wizard-step")) {
$("#back-step").hide();
$("#next-step").show();
}
else {
$("#back-step").show();
$("#next-step").show();
}
}
}
self.SubmitForm = function (formElement) {
$.ajax({
url: '#Url.Content("~/Complaint/Save")',
type: "POST",
data: ko.toJS(self),
done: function (result) {
var newDiv = $(document.createElement("div"));
newDiv.html(result);
},
fail: function (err) {
alert(err);
},
always: function (data) {
alert(data);
}
});
}
self.loadData = function () {
$.get({
url: '#Url.Content("~/Complaint/ViewComplaint")',
done: function (data) {
debugger;
alert(data);
self.compViewModel(data);
self.userViewModel(data);
},
fail: function (err) {
debugger;
alert(err);
},
always: function (data) {
debugger;
alert(data);
}
});
}
}
</script>
<form class="form-horizontal" role="form" id="myFrm">
<div class="container">
<div class="row">
<div class="col-md-3">
</div>
<div class="col-md-6">
<div class="wizard-step">
</div>
<div class="wizard-step" >
<h3> Step 2</h3>
#Html.Partial("UserView", Model.userViewModel)
<div class="col-md-3"></div>
<div class="col-md-6">
<input type="submit" id="submitButton" class="btn btn-default btn-success" value="Submit" data-bind="click: SubmitForm" />
</div>
<div class="col-md-3"></div>
</div>
<div class="wizard-step">
<h3> Step 3</h3>
</div>
<div class="wizard-step confirm">
<h3> Final Step 4</h3>
</div>
</div>
<div class="col-md-3"></div>
</div>
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<input type="button" id="back-step" class="btn btn-default btn-success" value="< Back" data-bind="click: Back" />
<input type="button" id="next-step" class="btn btn-default btn-success" value="Next >" data-bind="click: Next" />
</div>
<div class="col-md-3"></div>
</div>
</div>
</form>
I am able to get the data from controller and bind it using knockout. There is a partial view that loads data from controller. But when submitting the updated data, I do not get the data that was updated, instead getting error that "FirstName" property could not be accessed from null reference. I just need to get pointers where I am going wrong especially the right way to create ViewModels and use them.
When you are submitting the form in self.SubmitForm function you are passing Json object which is converted from Knockout view model.
So make sure you are providing the data-bind attributes in all input tags properly. If you are using Razor syntax then use data_bind in Html attributes of input tags.
Check 2-way binding of KO is working fine. I can't be sure as you have not shared your partial view Razor code.
Refer-
http://knockoutjs.com/documentation/value-binding.html
In Chrome you can see what data you are submitting in Network tab of javascript developer console. The Json data that you are posting and ViewModel data structure you are expecting in controller method should match.
You can also change the parameters to expect FormCollection formCollection and check what data is coming from browser when you are posting.