.each() not working in IE - jquery-selectors

I want to get all labels inside a div, the blow piece of code works in Firefox and not working IE. Any idea. Thanks in advance.
<div id='discounts'>
<label id="discount1"> discount 1</label>
<label id="discount2"> discount 2 </label>
<input type="text" id="discountmisc" value="" />
</div>
var selectLabels = {
getLabels: function() {
$('#discounts > label').each(function(index, item) {
alert(index + $(item).attr('id'));
});
}
};
selectLabels.getLabels();

Are you wrapped in DOM Ready functions? i.e.
$(function () {
var selectLabels = {
getLabels: function() {
$('#discounts > label').each(function(index, item) {
alert(index + $(item).attr('id'));
});
}
};
selectLabels.getLabels();
});
or alternately:
var selectLabels = {
getLabels: function() {
$('#discounts > label').each(function(index, item) {
alert(index + $(item).attr('id'));
});
}
};
$(selectLabels.getLabels);
or finally (because you don't care about the return value):
var selectLabels = {
getLabels: function() {
$(function () {
$('#discounts > label').each(function(index, item) {
alert(index + $(item).attr('id'));
});
});
}
};
selectLabels.getLabels();
Tell me, and if so, I'll change my answer.

Related

Knockout event binding with condition

I want to bind some events to an element , using the knockout "event" binding
But I want all of the listed events to be bound only with a specific case.
The viewmodel:
function vm(){
var self = this;
self.isEditMode = ko.observable(false);//can be changed to true
self.events = ko.observable({
down: function () {
console.log("down")
},
up: function () {
console.log("up")
},
hover: function () {
console.log("hover")
}
});
}
and the Html:
<div style="border:1px solid red;width:50px;height:50px"
data-bind="event:{mousedown:events().down,mouseup:events().up,mouseover:events().hover}:null"></div>
<button data-bind="click:function(){isEditMode(!isEditMode())}">change </button>
I tried:
<div data-bind="event:isEditMode()?{mousedown:events().down,mouseup:events().up,mouseover:events().hover}:null"></div>
But it did not work for me.
I think the best way to do it is by using custom bindingHandlers, but I dont know how.
Thank you very much for your help!
You can simplify the the binding by moving some logic into the view model
<div style="border:1px solid red;width:50px;height:50px"
data-bind="event: {
mousedown: down,
mouseup:up,
mouseover:hover }" > </div>
and view model like this
function vm() {
var self = this;
this.isEditMode = ko.observable(true);
down = function() {
if(this.isEditMode())
{
console.log("down")
}
};
up = function() {
if(this.isEditMode())
{
console.log("up")
}
};
hover = function() {
if(this.isEditMode())
{
console.log("hover")
}
};
}
var viewModel = new vm();
ko.applyBindings(viewModel);
Another option is to place the condition in the markup itself as two separate blocks using an "if" binding to determine which ones gets shown and bound.
function vm() {
var self = this;
self.isEditMode = ko.observable(false); //can be changed to true
self.events = ko.observable({
down: function() {
console.log("down");
},
up: function() {
console.log("up");
},
hover: function() {
console.log("hover");
}
});
}
ko.applyBindings(new vm());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<!--ko if: isEditMode()-->
<div style="border:1px solid red;width:50px;height:50px" data-bind="event:{
mousedown:events().down,
mouseup:events().up,
mouseover:events().hover
}">
Edit Mode
</div>
<!--/ko-->
<!--ko if: !isEditMode()-->
<div style="border:1px solid red;width:50px;height:50px">
Read Only
</div>
<!--/ko-->
<button data-bind="click:function(){isEditMode(!isEditMode())}">change </button>

updating text using knockout computed function

In a table I have a checkbox bound to a bool in an observable array.
If any of the checkboxes in the table are checked / unchecked I want to update some text with the total checked.
I cannot get the computed function to fire, I have tried using ko.utils.unwrapObservable on both the array and location.isSelected in the 'if' statement below, am I just using it in the wrong place?
<input type="checkbox" data-bind="checked: isSelected"/>
<span class="text-left h5 ">Total Selected:</span><span data-bind="text: totalSelected" />
self.totalSelected = ko.computed(function () {
var selected = 0;
ko.utils.arrayForEach(self.SelectedLocations(), function (location) {
if (location.isSelected == true) {
selected = (+selected) + 1;
}
});
return selected;
}, self).extend({ notify: 'always' });
One of the issues is that isSelected is treated like a variable inside the computed: location.isSelected == true. However, if you intend to bind a checkbox to it, it must be an observable.
So, I have declared a function to create the children of self.SelectedLocations as:
var locationObservable = function() {
var self = this;
self.isSelected = ko.observable(false);
};
Then, you could change the counting in the computed variable as follows:
if (loc.isSelected()) {
selected++;
}
var locationObservable = function(selected) {
var self = this;
self.isSelected = ko.observable(selected);
};
var model = function() {
var self = this;
self.SelectedLocations = ko.observableArray();
self.SelectedLocations.push(new locationObservable(false)); // Set the state of the checkbox here.
self.SelectedLocations.push(new locationObservable(true));
self.SelectedLocations.push(new locationObservable(false));
self.totalSelected = ko.computed(function() {
var selected = 0;
ko.utils.arrayForEach(self.SelectedLocations(), function(loc) {
if (loc.isSelected()) {
selected++;
}
});
return selected;
}, self);
};
var vm = new model();
ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div data-bind="foreach: SelectedLocations">
<input type="checkbox" data-bind="checked: isSelected" />
</div>
<span class="text-left h5 ">Total Selected:</span><span data-bind="text: totalSelected" />

React Form validation displaying error

I am using React-Validation-Mixin together with Joi and Joi-Validation-Strategy to do some validations on a React Step/Wizard Form.
I have a parent FormStart Element that receives the state of its FormStep children through props.
The validation correctly signals that the input is required, but when I write a correct number in the browser (5 numbers as in PLZ/ZIP-Code), it will still signal that the input is invalid, even though the zip state shows a correct 5-digit number, so the next button never takes me to the next Form step.
class FormStart extends Component {
constructor(props) {
super(props);
this.state = {
step: 1,
zip: ""
}
this.goToNext = this.goToNext.bind(this);
}
goToNext() {
const { step } = this.state;
if (step !== 10) {
this.setState({ step: step + 1 });
if (step == 9) {
const values = {
zip: this.state.zip,
};
console.log(values);
// submit `values` to the server here.
}
}
}
handleChange(field) {
return (evt) => this.setState({ [field]: evt.target.value });
}
render(){
switch (this.state.step) {
case 1:
return <FormButton
onSubmit={this.goToNext}
/>;
//omitting the other 8 cases
case 9:
return <FormStep7
onSubmit={this.goToNext}
zip={this.state.zip}
onZipChange={this.handleChange('zip')}
/>;
case 10:
return <FormSuccess/>;
}
}
}
export default FormStart;
The React console shows that the zip state is correctly changed, and the Validation object also receives the same correct 5-digit zip and still holds the correct value onBlur.
class FormStep7 extends Component {
constructor(props) {
super(props);
this.validatorTypes = {
PLZ: Joi.number().min(5).max(5).required().label('PLZ').options({
language: {
number: {
base: 'wird benötigt',
min: 'muss {{limit}} Nummern enthalten',
max: 'muss {{limit}} Nummern enthalten'
}
}
})
};
this.getValidatorData = this.getValidatorData.bind(this);
this.getClasses = this.getClasses.bind(this);
this.renderHelpText = this.renderHelpText.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
getValidatorData() {
return {
PLZ: this.props.zip
};
}
getClasses(field) {
return classnames({
'form-control': true,
'has-error': !this.props.isValid(field)
});
}
renderHelpText(message) {
return (
<span className='help-block'>{message}</span>
);
}
handleSubmit(evt) {
evt.preventDefault();
const onValidate = (error) => {
if (error) {
//form has errors; do not submit
} else {
this.props.onSubmit();
}
};
this.props.validate(onValidate);
}
render() {
return (
<form role="form" onSubmit={this.handleSubmit}>
<div className='row'>
<div className="col-md-10 col-md-offset-1">
<div className='form-group'>
<label htmlFor="zip">
Einsatzort
</label>
<br />
<input className={this.getClasses('PLZ')} id="PLZ" placeholder="Meine PLZ" type="text" onChange={this.props.onZipChange} onBlur={this.props.handleValidation('PLZ')} value={this.props.zip} />
{this.renderHelpText(this.props.getValidationMessages('PLZ'))}
</div>
</div>
</div>
<div className='row'>
<div className="col-md-10 col-md-offset-1">
<button className="btn btn-green btn-block">Next</button>
</div>
</div>
</div>
</form>
);
}
}
FormStep7.propTypes = {
errors: PropTypes.object,
validate: PropTypes.func,
isValid: PropTypes.func,
handleValidation: PropTypes.func,
getValidationMessages: PropTypes.func,
clearValidations: PropTypes.func
};
export default validation(strategy)(FormStep7);
What am I doing wrong?
I found out that the issue was on Joi.number(). I changed the validation to match a Regex String pattern and then it worked.
this.validatorTypes = {
PLZ: Joi.string().regex(/^[0-9]{5}$/).label('PLZ').options({
language: {
string: {
regex: {
base: "mit 5 Nummern wird benötigt"
}
}
}
})
};

populate select with datajson using React js

I'm trying to populate a select using React js, I'm using the example given on the react js docs(https://facebook.github.io/react/tips/initial-ajax.html) , which uses jquery to manage the ajax calling, I'm not able to make it work, so far i have this:
here the codepen : http://codepen.io/parlop/pen/jrXOWB
//json file called from source : [{"companycase_id":"CTSPROD","name":"CTS-Production"},{"companyc ase_id":"CTSTESTING","name":"CTS-Testing"}]
//using jquery to make a ajax call
var App = React.createClass({
getInitialState: function() {
return {
opts:[]
};
},
componentDidMount: function() {
var source="https://api.myjson.com/bins/3dbn8";
this.serverRequest = $.get(source, function (result) {
var arrTen = result[''];
for (var k = 0; k < ten.length; k++) {
arrTen.push(<option key={opts[k]} value={ten[k].companycase_id}> {ten[k].name} </option>);
}
}.bind(this));
},
componentWillUnmount: function() {
this.serverRequest.abort();
},
render: function() {
return (
<div>
<select id='select1'>
{this.state.opts}
</select>
</div>
);
}
});
ReactDOM.render(
<App />,
document.getElementById('root')
);
html
<div id="root"></div>
any idea how to make it works, thanks.
You need to call setState to actually update your view. Here's a workable version.
//json file called from source : [{"companycase_id":"CTSPROD","name":"CTS-Production"},{"companyc ase_id":"CTSTESTING","name":"CTS-Testing"}]
//using jquery to make a ajax call
var App = React.createClass({
getInitialState: function() {
return {
opts:[]
};
},
componentDidMount: function() {
var source="https://api.myjson.com/bins/3dbn8";
this.serverRequest = $.get(source, function (result) {
var arrTen = [];
for (var k = 0; k < result.length; k++) {
arrTen.push(<option key={result[k].companycase_id} value={result[k].companycase_id}> {result[k].name} </option>);
}
this.setState({
opts: arrTen
});
}.bind(this));
},
componentWillUnmount: function() {
this.serverRequest.abort();
},
render: function() {
return (
<div>
<select id='select1'>
{this.state.opts}
</select>
</div>
);
}
});
ReactDOM.render(
<App />,
document.getElementById('root')
);

How return Partial from Action getJSON

I'm having a problem with method using $.getJSON. It's very simple and it looks like that:
Take ID из DropDownlList CategoryId
<div id="partial" class="editor-label">
#* #Html.Partial("");*#
</div>
$(document).ready(function () {
$('#CategoryId').change(function () {
$.getJSON('/Publication/AjaxAction/' + this.value, {},
function (html) {
$("#partial").html(html);
alert("go");
});
});
});
send in
public ActionResult AjaxAction(int Id)
{
if (Request.IsAjaxRequest())
{
if (Id== 1)
{
ViewBag.SourceTypeId = new SelectList(db.SourceTypes, "Id", "Title");
ViewBag.CityId = new SelectList(db.Cities, "Id", "Title");
return Partial("_CreateStatya");
}
}
return PartialView();
}
Could you please tell me how to return Partial in ??
<div id="partial" class="editor-label">
#* #Html.Partial("");*#
</div>
$(document).ready(function ()
{ $('#CategoryId').change(function ()
{ $.get('#Url.Action("AjaxAction","Publication")',
{id:$('#CategoryId').val()}, function (html)
{ $("#partial").html(html);
alert("go"); },'html');
}); });