jQuery setTimeout function doesn't work - settimeout

function zIndex(parcaNumber1, parcaNumber2, Timeout) {
setTimeout(function () {
$(parcaNumber1).css("z-index", "2");
$(parcaNumber2).css("z-index", "1");
}, Timeout);
}
I have a function, but does not work.
what's wrong?

function zIndex(parcaNumber1, parcaNumber2, Timeout) {
setTimeout(function () {
alert('a'); //it's working
}, Timeout);
}
probably you transfer parameters parcaNumber1, parcaNumber2 as string, but call it like an object:
$(parcaNumber1).css("z-index","2");
try:
$('.' + parcaNumber1).css("z-index","2");
or
$('#' + parcaNumber1).css("z-index","2");

Well, don't know what you are trying to do, but check this out: I made a demo.
See if it's what you are looking for. Don't forget to set divs with position: absolute;
Example:
HTML:
<div id="test"></div>
<div id="subtest"></div>
<input type="button" id="but" value="go" />
JavaScript:
$("#but").click(function(){
zIndex('#test', '#subtest', 1000);
});
function zIndex(parcaNumber1, parcaNumber2, Timeout) {
setTimeout(function () {
$(parcaNumber1).css("z-index","2");
$(parcaNumber2).css("z-index", "1");
}, Timeout);
}

Related

How to submit radio button value + additional info about the form to Redux

This is a bit longwinded so I'll do my best to explain clearly.
I'm making a simple poll app and on the home page is an array of polls where you can vote on each poll.
Each poll is on a card and there will be different radio buttons representing the different voting options for that poll.
I'm trying to set up a form for each poll which contains radio button inputs for each of the different options and push that onSubmit to an action creator.
However, I would also like to pass that title of the poll as well as an argument to the action creator so that I can create a single action creator that will help me submit the votes for all the polls. Something like submitVote(title, option).
Here is my polls page:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as actions from '../../actions';
import Loading from '../Loading';
class MyPolls extends Component {
constructor(props) {
super(props);
this.state = {
skip: 0,
isLoading: true,
isLoadingMore: false,
value: ''
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
componentDidMount() {
this.props.fetchMyPolls(this.state.skip)
.then(() => {
setTimeout(() => {
this.setState({
skip: this.state.skip + 4,
isLoading: false
});
}, 1000);
});
}
sumVotes(acc, cur) {
return acc.votes + cur.votes
}
loadMore(skip) {
this.setState({ isLoadingMore: true });
setTimeout(() => {
this.props.fetchMyPolls(skip)
.then(() => {
const nextSkip = this.state.skip + 4;
this.setState({
skip: nextSkip,
isLoadingMore: false
});
});
}, 1000);
}
handleSubmit(e) {
e.preventDefault();
}
handleChange(event) {
console.log(event.target.value);
this.setState({ value: event.target.value });
}
renderPolls() {
return this.props.polls.map(poll => {
return (
<div className='card' key={poll._id} style={{ width: '350px', height: '400px' }}>
<div className='card-content'>
<span className='card-title'>{poll.title}</span>
<p>Total votes: {poll.options.reduce((acc, cur) => { return acc + cur.votes }, 0)}</p>
<form onSubmit={this.handleSubmit}>
{poll.options.map(option => {
return (
<p key={option._id}>
<input
name={poll.title}
className='with-gap'
type='radio'
id={option._id}
value={option.option}
onChange={this.handleChange}
/>
<label htmlFor={option._id}>
{option.option}
</label>
</p>
)
})}
<button
type='text'
className='activator teal btn waves-effect waves-light'
style={{
position: 'absolute',
bottom: '10%',
transform: 'translateX(-50%)'
}}
>
Submit
<i className='material-icons right'>
send
</i>
</button>
</form>
</div>
<div className='card-reveal'>
<span className='card-title'>{poll.title}
<i className='material-icons right'>close</i>
</span>
<p>
dsfasfasdf
</p>
</div>
</div>
)
})
}
render() {
return (
<div className='center-align container'>
<h2>My Polls</h2>
{this.state.isLoading ? <Loading size='big' /> :
<div style={{ display: 'flex', flexWrap: 'wrap', justifyContent: 'space-evenly', alignItems: 'center', alignContent: 'center' }}>
{this.renderPolls()}
</div>}
<div className='row'>
{this.state.isLoadingMore ? <Loading size='small' /> :
<button
className='btn red lighten-2 wave-effect waves-light' onClick={() => this.loadMore(this.state.skip)}>
Load More
</button>}
</div>
</div>
);
}
}
function mapStateToProps({ polls }) {
return { polls }
}
export default connect(mapStateToProps, actions)(MyPolls);
Demo of the app so far: https://voting-app-drhectapus.herokuapp.com/
(use riverfish#gmail.com and password 123 to login).
Github repo: https://github.com/drhectapus/Voting-App
I'd like to program it so that when form is submitted via this.handleSubmit, the handleSubmit function can take 2 arguments, title and option and pass that onto an action creator in redux.
How do I do this?
It's a little difficult to understand everything going on here, but I get the sense that your main goal is to pass two args to this.handleSubmit. You may instead consider just passing poll.title and grabbing the selected option from state. Try something like this:
this.handleSubmit(title) {
// this.state.value should already have the selected option!
let obj = {
title,
option: this.state.value
};
// dispatch the object to redux, update your reducer, etc.
}
And in your render, be sure to bind poll.title as the argument:
render() {
...
<form onSubmit={this.handleSubmit.bind(this, poll.title)}>
}
Does that help at all? Let me know if I'm totally missing the mark on what you intend. With .bind() you pass the this context to use followed by a list of common separated args, so you could pass multiple args, but it's much easier to just grab option from state in this case.
Edit
If you want to access the SyntheticEvent that gets fired on submit, you simple specify it as the second argument to this.handleSubmit like so:
this.handleSubmit(title, event) {
// prevent form submit
event.preventDefault();
}
// this is the exact same as above, no need to pass event
render() {
...
<form onSubmit={this.handleSubmit.bind(this, poll.title)}>
}
In React, synthetic events are always passed as the last argument to a bound function and simply need to be specified to be in the method definition (no need to specify in render). This is Function.prototype.bind way of working with functions and events in React. Here are the supporting docs: https://reactjs.org/docs/handling-events.html#passing-arguments-to-event-handlers

wrong value for parameter wsServers

i'm using freeswitch 1.6 and following cookbok to implement webrtc. for this i download sip.js#0.7.0 too. and have created call.html, call.js and answer.html, answer.js pages. my call.html including js is
<html>
<body>
<button id="startCall">Start Call</button>
<button id="endCall">End Call</button>
<br/>
<video id="remoteVideo"></video>
<br/>
<video id="localVideo" muted="muted" width="128px" height="96px"></video>
<!--<script src="js/sip-0.7.0.min.js"></script>-->
<!--<script src="call.js"></script>-->
</body>
<HEAD>
<script src="js/sip-0.7.0.min.js"></script>
<script>
var session;
console.log('hiiiiiiiiiiii')
var endButton = document.getElementById('endCall');
endButton.addEventListener("click", function () {
session.bye();
alert("Call Ended");
}, false);
console.log('hiiiii2')
var userAgent = new SIP.UA({
uri: 'sip:anonymous#gmaruzz.org',
wsServers: ["ws://call.sia.co.in:5066"],
authorizationUser: 'anonymous',
password: 'welcome'
});
console.log('hiiii3')
var startButton = document.getElementById('startCall');
startButton.addEventListener("click", function () {
session =userAgent.invite('sip:1010#139.59.17.63', options);
alert("Call Started");
}, false);
console.log('hiiii4')
var options = {
media: {
constraints: {
audio: true,
video: true
},
render: {
remote:document.getElementById('remoteVideo'),
local: document.getElementById('localVideo')
}
}
};
</script>
</HEAD>
</html>
please correct me where i'm going wrong. Thanks in advance.
you must put the wsServers in transportOptions like :
var userAgent = new SIP.UA({
uri: 'sip:anonymous#gmaruzz.org'
transportOptions: {
wsServers: "ws://call.sia.co.in:5066"
},
authorizationUser: 'anonymous',
password: 'welcome'

Using Protractor: Switch to iframe using browser.switchTo().frame

So I have already written the testing script which:
1) Logs into the application framework, then
2) Clicks menu to launch the app which I am testing ("MyAwesomeApp.html" for this post)
And my main problem is: In navpanel-spec.js below, I want to target the https://server/apps/Default.aspx?r=1 URL, then click within the iframe where MyAwesomeApp is running.
**** ERROR Trying to switch to the iframe this way, but it does NOT work:
browser.switchTo().frame(element(by.id('1')).getWebElement());
Error in cmd prompt:
Started
[15:43:29] E/launcher - No element found using locator: By(css selector, *[id="\31 "])
...
sat-navpanel-spec.js:52:24)
So there are two URLs going on here:
1) https://server/apps/Default.aspx?r=1 (the main app framework with menu system in top nav).
2) https://server/apps/MyAwesomeApp.html (the web app which the test script launches within the <iframe> tag.
The html looks like this, where the application renders within the <iframe> :
<body>
<div id="top">
<!-- top nav menu systems rendered here -->
</div>
<div id="middle">
<div id="m1">
<div id="m2" class="hidden">
<div id="m3">
<div id="right" class="hidden">
<div>
<div id="frame_holder" style="height: 940px;">
<iframe style="width: 100%; height: 100%;" name="1" id="1" src="https://server/apps/MyAwesomeApp.html">
</iframe>
</div>
</div>
</div>
</div>
<div id="left" style="display: none;"></div>
</div>
</div>
</div>
</body>
In my Protractor.config.js file I have a few specs :
specs: [
'spec/login.js',
'spec/launch-awesome-app.js',
'spec/navpanel-spec.js',
'spec/another-spec.js',
'spec/yet-another-spec.js'
]
login.js and launch-awesome-app.js work fine. They log into the menu system, then click thru the menus in order to launch myAwesomeapp - no problem.
MY PROBLEM:
In navpanel-spec.js I want to target the https://server/apps/Default.aspx?r=1 URL, then click within the iframe where MyAwesomeApp is running.
However, it is NOT selecting any of my elements.
If I target https://server/apps/MyAwesomeApp.html in navpanel-spec.js, of course it launches a new browser window and runs the test just fine.
Here's my navpanel-spec.js test spec:
describe('Testing My Awesome App', function () {
var panelObj = new PanelObjects();
var urlDefault = 'https://server/apps/Default.aspx?r=1';
var urlApp = 'https://server/apps/MyAwesomeApp.html';
browser.get(urlApp); // Runs my AwesomeApp tests okay, HOWEVER it launches a new browser window.
browser.get(urlDefault); // Launches app framework with top nav menus and embedded <iframe>,
// HOWEVER I cannot select iframe and successfully run tests here.
beforeEach(function () {
browser.sleep(5000);
browser.waitForAngular();
});
// USE-CASE OBJECT !!
var items = browser.params.useCaseJsonFile["navigatePanels"];
browser.getAllWindowHandles().then(function (handles) {
handles.map(function (win, idx) {
browser.driver.getCurrentUrl().then(function (curr) {
if (curr.indexOf('Default.aspx') >= 0) {
browser.driver.switchTo().window(handles[idx]);
}
});
});
});
browser.switchTo().frame(element(by.id('1')).getWebElement());
var testId = element(by.id('middle'));
console.log(testId);
items.map(function (item) {
if (item.enableTest) {
var specItem = it(item.name, function () {
console.log('------------------------------');
console.log('---- ' + item.describe);
browser.waitForAngular();
// select panels, etc..
panelObj.panelClick(item.panelName).then(function () {
// ...
});
panelObj.getPanelText(item.panelName).then(function (title) {
expect(title).toContain(item.panelTitle);
});
});
}
});
});
UPDATE
var LoginObjects = require('../pageObjects/login-objects.js');
describe('Testing My Awesome App', function () {
var panelObj = new PanelObjects();
var loginObj = new LoginObjects();
//var urlDefault = 'https://server/apps/Default.aspx?r=1';
//browser.get(urlApp); // Runs my AwesomeApp tests okay, HOWEVER it launches a new browser window.
browser.ignoreSynchronization = true;
// LOGIN AND LAUNCH APP !!!
loginObj.Login();
loginObj.Launch();
beforeEach(function () {
browser.sleep(5000);
browser.waitForAngular();
});
// USE-CASE OBJECT !!
var items = browser.params.useCaseJsonFile["navigatePanels"];
// SWITCH TO iframe ELEMENT
loginObj.switchWindowAndFrame();
items.map(function (item) {
if (item.enableTest) {
var specItem = it(item.name, function () {
console.log('------------------------------');
console.log('---- ' + item.describe);
browser.waitForAngular();
// select panels, etc..
panelObj.panelClick(item.panelName).then(function () {
// ...
});
panelObj.getPanelText(item.panelName).then(function (title) {
expect(title).toContain(item.panelTitle);
});
});
}
});
});
and my page objects :
module.exports = function(){
this.Login = function(){
var url = browser.params.loginUrl;
browser.driver.get(url);
browser.sleep(200);
var userName = browser.params.credential.userId;
var password = browser.params.credential.password;
element(by.id('username')).clear().then(function(){
element(by.id('username')).sendKeys(userName);
element(by.id('password')).sendKeys(password);
});
browser.sleep(1000);
var that = this;
var submitElement = element(by.id('bthLogin'));
submitElement.click().then(function () {
browser.getAllWindowHandles().then(function (handles) {
// LOGIN MESSAGE WINDOW
browser.driver.getCurrentUrl().then(function(curr){
if (curr.indexOf('LoginMsg.aspx') >= 0){
// Do we really need to close the login successful browser ???
browser.driver.close();
}
});
browser.driver.switchTo().window(handles[1]);
});
});
},
this.Launch = function(){
var sel = '#TheMenu1 > ul > li:first-child';
var elem = element(by.css(sel));
elem.click().then(function(){
browser.sleep(1000);
var elem2 = element(by.cssContainingText('.rmLink', 'The First Menu Item'));
elem2.click();
// Select menu item; sleep before attempting to click().
var subElem = element(by.cssContainingText('.rmLink', 'My Awesome App'));
browser.sleep(1000);
subElem.click();
browser.waitForAngular();
});
},
this.switchWindowAndFrame = function(){
browser.getAllWindowHandles().then(function (handles) {
handles.map(function(win, idx){
browser.driver.getCurrentUrl().then(function(curr){
if (curr.indexOf('Default.aspx') >= 0){
browser.driver.switchTo().window(handles[idx]);
}
});
});
});
browser.switchTo().frame(element(by.css('[name="1"]')).getWebElement());
}
};
As mentioned in the comments above, protractor has a bug which prefixes '\3' to your id element with number.
The temporary way is to change you locator. :P

angularjs $resource : can't $save JSON

starting with angular, i am trying to GET data from the server and then POST back modifications with $resources.
It's working fine except the "save" function. No Data is POSTed back to the server.
here is the html
<div ng-controller="myCtrl">
<div ng-repeat="obj in objs">
<h2>{{obj.data_1}}</h2>
<h3>{{obj.data_2}}</h3>
<input type='text' ng-model="obj.data_1"><br/>
<textarea ng-model="obj.data_2" required></textarea><br/>
<button ng-click="save()">Save</button>
</div>
</div>
service.js
'use strict';
angular.module('App.services', ['ngResource']).
factory('Obj', function($resource){
return $resource('url/to/json');
});
controller.js:
'use strict';
angular.module('App.controllers', []).
controller('myCtrl', ['$scope', 'Obj', function($scope, Obj) {
$scope.objs = Obj.query();
$scope.save = function() {
$scope.objs.save();
}
}]);
Do you know why nothing is POSTed back when i save ?
Using the query method on the $resource object implies return as follows 'query': {method:'GET', isArray:true} it's mean that your $scope.objs is an array of objects and not an object and depending on number of elements you can use the folowing notation:
$scope.objs[i].save()
where i is the index of element in the array, forexample if you have return like:
[ {id:1, name:'Some name', age:35} ];
then your code : $scope.objs[0].save()
Edit:
I have created a plunk, maybe it will help you... http://plnkr.co/edit/62iPCAUNjV0oJROhul1G
Shouldn't there be another $resource declared for POST the way it is declared for GET? Each $resource specify particular REST service.
//services.js
'use strict';
angular.module('App.services', ['ngResource'])
.factory('GetObj', function($resource){
return $resource('url/to/json');
}
.factory('SaveObj', function($resource){
return $resource('url/to/post');
});
//controller.js
'use strict';
angular.module('App.controllers', []).
controller('myCtrl', ['$scope', 'GetObj', 'SaveObj', function($scope, GetObj, SaveObj) {
$scope.objs = Obj.query();
$scope.save = SaveObj.save(objs, function(resp) {
//Callback
console.log("Response from POST: %j", resp);
}
}]);

Jquery, Validate, Submit Form to PHP (Ajax Problem)

Very early days playing Javascript, Jquery and Validate.
I am using the Submit Button onClick method for form submission.
<input class="submit" type="submit" value="Submit" onClick="submitForm()" />
I am using the submit, in case no data or not every field has been tested.
The logic is working, but the AJAX call does not appear to be working. I have stripped down the PHP to
<?php
touch('phpTouch.txt');
phpinfo();
sleep(30;)
?>
The javascript is
$(document).ready(function () {
$('#formEnquiry').validate();
});
function submitForm() {
$('#msgid').append('<h1>Submitting Form (External Routine)</h1>');
if ($('#formEnquiry').validate().form() ) {
$("#msgid").append("<h1>(Outside Ready) VALIDATED send to PHP</h1>");
$.ajax({
url: "testPHP.php",
type: "POST",
data: frmData,
dataType: "json",
success: function () {
alert("SUCCESS:");
},
error: function () {
alert("ERROR: ");
}
});
} else {
$('#msgid').append('<h1>(Outside Ready) NOT VALIDATED</h1>');
}
return false; // Prevent the default SUBMIT function occurring (is this a fact ??)
};
Can anyone advise as to what I am doing wrong.
Thanks
Do these things
Change onClick="submitForm()" on the HTML markup to onclick="submitForm(event)"
Now change the submitForm function like this.
function submitForm(evt) {
$('#msgid').append('<h1>Submitting Form (External Routine)</h1>');
if ($('#formEnquiry').valid() ) {
$("#msgid").append("<h1>(Outside Ready) VALIDATED send to PHP</h1>");
$.ajax({
url: "testPHP.php",
type: "POST",
data: frmData,
contentType: "application/json;",
success: function () {
alert("SUCCESS:");
},
error: function (a, b, c) {
alert(a.statusText);
}
});
} else {
$('#msgid').append('<h1>(Outside Ready) NOT VALIDATED</h1>');
}
evt.preventDefault();
};
Please note these things
Check .valid() to determine form validity
Call .preventDefault() instead of return false; ( Its more jQuery-ish )