I'm trying to have three radio buttons for three mutually exclusive choices in a form. The form also includes a text input and textarea. Upon clicking the submit button, the value of the checked radio button and that of the text input and textarea need to be assigned as values for props.
var Widget = React.createClass({
render: function() {
var widgetClasses = classNames('widget', this.props.widgetWidth);
return (
<div className={widgetClasses}>
<header className="widget-header">
<h3>{this.props.widgetTitle}</h3>
<p>{this.props.widgetDescription}</p>
</header>
<ul>
<li>Lorem ipsum</li>
</ul>
<ul>
<li>Dolor sit</li>
</ul>
</div>
)
}
});
var WidgetsContainer = React.createClass({
render: function() {
var widgetNodes = this.props.data.map(function(widget) {
return (
<Widget widgetTitle={widget.widgetTitle}
widgetWidth={widget.widgetWidth}
widgetDescription={widget.widgetDescription}>
</Widget>
);
});
return (
<div className="widgetsContainer">
{widgetNodes}
</div>
);
}
})
var Dashboard = React.createClass({
getInitialState: function() {
return {data: []}
},
handleWidgetConfig: function(widget) {
var widgets = this.state.data;
// var widget.id = Date.now();
var newWidgets = widgets.concat([widget]);
this.setState({data: newWidgets});
},
render: function() {
var displayedItems = this.state.data;
return (
<div className="dashboard-content">
<CreateWidgetDropdown updateWidgetConfig={this.handleWidgetConfig} />
<WidgetsContainer data={displayedItems} />
</div>
);
}
});
var CreateWidgetDropdown = React.createClass({
createNewWidget: function(e) {
e.preventDefault();
var widgetWidth = this.refs.widgetWidthInput.checked.value;
var widgetTitle = this.refs.widgetTitleInput.value;
var widgetDescription = this.refs.widgetDescriptionInput.value;
this.props.updateWidgetConfig({
widgetWidth: widgetWidth,
widgetTitle: widgetTitle,
widgetDescription: widgetDescription
});
},
render: function() {
return (
<div className="page-dropdown">
<div className="page-dropdown-header">
<h2 className="wrapper">Add a Widget</h2>
</div>
<div id="page-dropdown-content">
<form className="page-dropdown-form">
<div classNameName="choose-widget-type">
<h3>Choose a Widget Type</h3>
<div className="widget-type table">
<h4>Table</h4>
<div classNameName="widget-type-icon">
<img src="" alt="" />
</div>
<ul className="widgetWidth">
<li>
<label for="1/3 Width input">
1/3 Width
<input ref="widgetWidthInput" name="widgetWidth" type="checkbox" value="1/3 Width" />
</label>
</li>
<li>
<label for="2/3 Width input">
2/3 Width
<input ref="widgetWidthInput" name="widgetWidth" type="checkbox" value="2/3 Width" />
</label>
</li>
<li>
<label for="Full Width input">
Full Width
<input ref="widgetWidthInput" name="widgetWidth" type="checkbox" value="Full Width" />
</label>
</li>
</ul>
</div>
<div classNameName="create-widget-header">
<h3>Widget Header (Optional)</h3>
<label for="widget-title-input">
Widget Title (30 characters max)
<input type="text" ref="widgetTitleInput" required />
</label>
<label for="widget-description-input">
Widget Description (50 characters max)
<textarea ref="widgetDescriptionInput"></textarea>
</label>
<button onClick={this.createNewWidget}>Add Widget</button>
<button type="reset">Cancel</button>
</div>
</form>
</div>
</div>
)
}
});
ReactDOM.render(<Dashboard />, document.getElementById('dashboard-container'));
I would suggest you use an <input type="radio"> instead of <input type="checkbox">:
<ul className="widgetWidth">
<li>
<label>
1/3 Width
{' '}
<input name="width" type="radio" value="1/3 Width" defaultChecked/>
</label>
</li>
<li>
<label>
2/3 Width
{' '}
<input name="width" type="radio" value="2/3 Width" />
</label>
</li>
<li>
<label>
Full Width
{' '}
<input name="width" type="radio" value="Full Width" />
</label>
</li>
</ul>
Then if you use the form's onSubmit event...
<form className="page-dropdown-form" onSubmit={this.createNewWidget}>
...and give all your inputs name attributes, you can use the form's elements collection to get all the values you need with refs, and the radio input's value can be obtained using the .value getter on the collection it's represented by in form.elements:
createNewWidget(e) {
e.preventDefault()
var form = e.target
var width = form.elements.width.value
var title = form.elements.title.value
var description = form.elements.description.value
this.props.updateWidgetConfig({
width,
title,
description,
})
},
Live example: http://stackoverflow-38236634.surge.sh/
Gist you can clone to develop (with hot reloading) and build this example: https://gist.github.com/insin/45b7f66e01628601c0cc6b79767b0e4f
Full code for the working example:
var classNames = require('classnames')
var React = require('react')
var ReactDOM = require('react-dom')
var uuid = require('uuid')
var Widget = React.createClass({
render() {
var {widget} = this.props
var widgetClasses = classNames('widget', widget.width)
return <div className={widgetClasses}>
<header className="widget-header">
<h3>{widget.title}</h3>
<p>{widget.description}</p>
</header>
<ul>
<li>Lorem ipsum</li>
</ul>
<ul>
<li>Dolor sit</li>
</ul>
</div>
}
})
var WidgetsContainer = React.createClass({
render() {
return <div className="widgetsContainer">
{this.props.data.map(widget =>
<Widget key={widget.id} widget={widget}/>
)}
</div>
}
})
var Dashboard = React.createClass({
getInitialState() {
return {
data: []
}
},
handleWidgetConfig(widget) {
this.setState({
data: [
...this.state.data,
{id: uuid.v4(), ...widget},
]
})
},
render() {
return <div className="dashboard-content">
<CreateWidgetDropdown updateWidgetConfig={this.handleWidgetConfig} />
<WidgetsContainer data={this.state.data} />
</div>
}
})
var CreateWidgetDropdown = React.createClass({
createNewWidget(e) {
e.preventDefault()
var form = e.target
var width = form.elements.width.value
var title = form.elements.title.value
var description = form.elements.description.value
this.props.updateWidgetConfig({
width,
title,
description,
})
},
render() {
return <div className="page-dropdown">
<div className="page-dropdown-header">
<h2 className="wrapper">Add a Widget</h2>
</div>
<div id="page-dropdown-content">
<form className="page-dropdown-form" onSubmit={this.createNewWidget}>
<div className="choose-widget-type">
<h3>Choose a Widget Type</h3>
<div className="widget-type table">
<h4>Table</h4>
<div className="widget-type-icon">
<img src="" alt="" />
</div>
<ul className="widgetWidth">
<li>
<label>
1/3 Width
{' '}
<input name="width" type="radio" value="1/3 Width" defaultChecked/>
</label>
</li>
<li>
<label>
2/3 Width
{' '}
<input name="width" type="radio" value="2/3 Width" />
</label>
</li>
<li>
<label>
Full Width
{' '}
<input name="width" type="radio" value="Full Width" />
</label>
</li>
</ul>
</div>
<div className="create-widget-header">
<h3>Widget Header (Optional)</h3>
<label>
Widget Title (30 characters max)
{' '}
<input type="text" name="title" required />
</label>
<label>
Widget Description (50 characters max)
{' '}
<textarea name="description"></textarea>
</label>
</div>
<button type="submit">Add Widget</button>
<button type="reset">Cancel</button>
</div>
</form>
</div>
</div>
}
})
ReactDOM.render(<Dashboard />, document.getElementById('app'))
Related
As shown below, I tried to make a script to filter posts based on different checkboxes' values but I ended up having untargeted posts.
The problem I'm having is located in the match() method (I guess). I tried using the '&&' operator but that couldn't help.
I want to have posts based on the checkboxes I checked.
Thanks in advance!
Link: https://codepen.io/resourceful_geek/pen/JjvWLEj
var $filterCheckboxes = $('.filter-container input[type=checkbox]');
var posts = ".post";
$filterCheckboxes.on("change keyup", function() {
//var filteredCheckboxesSample = ['translation', 'proofreading', 'intermediate', 'expert', '1'];
//var textStringSample = filteredCheckboxes.toString();
var selectedFilters = {};
var textString = "";
$filterCheckboxes.filter(':checked').each(function() {
if (!selectedFilters.hasOwnProperty('filter')) {
selectedFilters['filter'] = [];
}
selectedFilters['filter'].push(this.value);
textString = selectedFilters['filter'].toString();
})
$(posts).hide().filter(function() {
var rtnData = "";
regExAll = new RegExp(textString.split(",").map(x => x.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')).join('|'), 'i');
rtnData = (
$(this).attr("data-category").match(regExAll) || $(this).attr("data-level").match(regExAll)
);
return rtnData;
}).show();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Filtered Posts</h1>
<div class="post-container">
<div class="post" data-id="1" data-job="translator" data-name="John" data-date="2021" data-level="beginner" data-price="20" data-rate="1" data-verified="1" data-category="translation">Translation | Beginner</div>
<div class="post" data-id="2" data-job="proofreader" data-name="Peter" data-date="2021" data-level="expert" data-price="20" data-rate="5" data-verified="1" data-category="proofreading">proofreading | expert</div>
<div class="post" data-id="3" data-job="translator" data-name="Steve" data-date="2021" data-level="intermediate" data-price="20" data-rate="1" data-verified="1" data-category="translation">Translation | intermediate</div>
<div class="post" data-id="4" data-job="content_crafting" data-name="Bil" data-date="2021" data-level="beginner" data-price="20" data-rate="2" data-verified="0" data-category="content_crafting">content_crafting | Beginner</div>
<div class="post" data-id="5" data-job="translator" data-name="Noah" data-date="2021" data-level="intermediate" data-price="20" data-rate="1" data-verified="0" data-category="translation">Translation | intermediate</div>
</div>
<h1>Filtering Area</h1>
<div class="filter-container">
<p>Filter by Category</p>
<div>
<input class="translation" type="checkbox" id="translation" name="service_categories" value="translation"></label>
<label for="translation">translation
</div>
<div>
<input class="proofreading" type="checkbox" id="proofreading" name="service_categories" value="proofreading"></label>
<label for="proofreading">proofreading
</div>
<div>
<input class="content_crafting" type="checkbox" id="content_crafting" name="service_categories" value="content_crafting"></label>
<label for="content_crafting">content_crafting
</div>
<p>Filter by Level</p>
<div>
<input class="beginner" type="checkbox" id="beginner" name="service_categories" value="beginner"></label>
<label for="beginner">beginner
</div>
<div>
<input class="intermediate" type="checkbox" id="intermediate" name="service_categories" value="intermediate"></label>
<label for="intermediate">intermediate
</div>
<div>
<input class="expert" type="checkbox" id="expert" name="service_categories" value="expert"></label>
<label for="expert">expert
</div>
</div>
I am trying to have a user set a function variable with an input number. I have a form they enter a number into, which needs to set the col const up top.
So far, i am using a simple hook, and col is being set (i console logged it), but its not producing the desired array. Im thinking its something getting messed up in the toggling at the bottom of the code.
function DataFrame(){
const [toggle, setToggle] = React.useState(false);
const [col, setCol] = useState(0)
var element = <li class="element"/>
var row = 3
var arr = []
var i
for (i = 0; i<row; i++){
arr.push(element)
}
const Element = () => <li className="element" />;
console.log(col)
return (
<div>
<div >
<div style={{fontFamily:'PressStart2P',opacity:'45%', width:'360px',
position:'absolute',left:'36px', top: '160px',color:'rgb(143, 0, 145)'}}>
</div>
<div >
<h1 class="dfHeader" style={{left:'30px'}}>
DataFrames :<br></br></h1>
<h1 class='dfHeader2'style={{top:'150px',left:'30px'}}>
constructor</h1>
<div class="codeBorder" style={{scrollbarColor:'#6a00ff'}}>
<div class="textbox" style={{width:'180px'}}>
<p class="instructions"></p>
<p class="instructions2"></p>
<p class="instructions3">
<form class="codeForm">
<label>
enter dimensions:
<input type="number" name="dimension" onKeyUp=
{e => setCol(e.target.value)} />
</label>
<input class='goButton' type="submit" value="run" />
</form>
<br/><br/></p>
<p class="instructions3">
<form class="codeForm">
<label>
input code:
<input type="number" name="dimension" />
</label>
<input class='goButton' type="submit" value="run" />
</form></p>
<p class="instructions3">
<form class="codeForm">
<label>
input code:
<input type="number" name="dimension" />
</label>
<input class='goButton' type="submit" value="run" />
</form></p>
<p class="instructions3">
<form class="codeForm">
<label>
input code:
<input type="number" name="dimension" />
</label>
<input class='goButton' type="submit" value="run" />
</form> </p>
</div>
</div>
<div class="btnConsole">
<button class="dfButton" onClick={()=>setToggle( (prev) => (!prev) )}>
</button>
</div>
</div>
<div class="monitor"style={{}}>
<div class="superScreen">
<div class="screenDiv" >
<div id="subScreen" class="subScreen">
{[...Array(col).keys()].map(ul => (
<ul key={ul}>
{toggle &&
[...Array(row).keys()].map(
li => <Element key={li} />)}
</ul>
))}
</div>
</div>
</div>
</div>
<br/>
</div>
</div>
)
}
export default DataFrame;
ReactDOM.render(<DataFrame />, document.getElementById('root'));
Any help is appreciated as always!
onKeyUp={e => setCol(e.target.value)}
this is the cause of your problem. e.target.value is a string, you are setting col equal to a string. Consequently, [...Array(col).keys()] gives you an array of length 1.
const col = '5';
console.log([...Array(col).keys()]);
Change
onKeyUp={e => setCol(e.target.value)}
to
onKeyUp={e => setCol(Number(e.target.value))}
In last question I had assistance to create a code to save the state of a fairly complex toggle state. When a radio button is selected a checkbox slides down, when that checkbox is selected another one slides down. The reverse also occurs. Much of the code I do not understand. The problem now is that it works perfectly in jsfiddle.
https://jsfiddle.net/tomik23/ovysmutL/7/
However, it does not function on my webpage. When localstorage restores the state back to the webpage after a page refresh it automatically 'unchecks' the checkboxes about 2 seconds after load when they should have remained checked.
I totally stripped down my page to try to isolate this issue...the problem still exists. I read and tried all the similar stackoverflow problems eg( modified forms, added doc ready function,etc)... but obviously none of them helped.
The code works prior to localstorage insertion. When page is refreshed localstorage restores the state back to the webpage but it automatically 'unchecks' the checkboxes about 2 seconds after load when they should have remained checked. Does ANYBODY know what is going on AND HOW TO FIX THIS? I truly appreciate the help.
**HTML**
<form class="form" id="form-a" method="post" autocomplete="on">
<fieldset>
<div>
<p>
<label class="yes_text">Yes</label>
<span>
<input type="radio" data-show="next-a" id="dog" name="answer_name" value="yes">
</span>
</p>
<p>
<label>No</label>
<span>
<input type="radio" name="answer_name" value="no" checked>
</span>
</p>
</div>
</fieldset>
<fieldset id="next-a" class="hidden">
<div class="red">
<div>
<p>Include Red Dogs:</p>
</div>
<div>
<p>
<label class="yes_text_include">select to include</label>
<span>
<input type="checkbox" data-show="next-b" id="cat" class="red" name="red_name" value="">
</span>
</p>
</div>
</div>
<div id="next-b" class="hidden">
<div>
<p>Include Green Dogs:</p>
</div>
<div>
<p>
<label>select to include</label>
<span>
<input type="checkbox" name="green_name" class="cat" value="">
</span>
</p>
</div>
<div>
<p>
<label>select to include</label>
<span>
<input type="checkbox" name="blue_name" class="cat" value="">
</span>
</p>
</div>
</div>
</fieldset>
</form>
<form class="form" id="form-b" method="post" autocomplete="on">
<fieldset>
<div>
<p>
<label class="yes_text">Yes</label>
<span>
<input type="radio" data-show="next-a" id="dog" name="answer_name" value="yes">
</span>
</p>
<p>
<label>No</label>
<span>
<input type="radio" name="answer_name" value="no" checked>
</span>
</p>
</div>
</fieldset>
<fieldset id="next-a" class="hidden">
<div class="red">
<div>
<p>Include Red Dogs:</p>
</div>
<div>
<p>
<label class="yes_text_include">select to include</label>
<span>
<input type="checkbox" data-show="next-b" id="cat" class="red" name="red_name" value="">
</span>
</p>
</div>
</div>
<div id="next-b" class="hidden">
<div>
<p>Include Green Dogs:</p>
</div>
<div>
<p>
<label>select to include</label>
<span>
<input type="checkbox" name="green_name" class="cat" value="">
</span>
</p>
</div>
</div>
</fieldset>
</form>
**Javascript**
class CheckForm {
constructor(option) {
const forms = document.querySelectorAll(`${option}`);
forms.forEach(form => {
const formname = form.id;
this.formCheck(formname);
this.checkChecked(formname);
});
}
formCheck(formName) {
const form = document.querySelector(`#${formName}`);
form.addEventListener('click', e => {
const { target: { type, value, id, dataset: { show } } } = e;
switch (type) {
case 'radio': {
if (value === 'yes') {
$(`#${formName}`).find(`#${show}`).show(200);
this.saveToLocalstore(formName);
} else {
$(`#${formName} fieldset`).next().hide(200);
document.querySelector(`#${formName}`).reset();
localStorage.removeItem(formName);
this.removeAllChecked(formName);
}
break;
}
case 'checkbox': {
$(`#${formName}`).find(`#${show}`).toggle(200);
this.saveToLocalstore(formName);
if (id) {
this.removeAllChecked(formName, id);
}
break;
}
default:
break;
}
});
}
saveToLocalstore(formName) {
let allInput = document.querySelectorAll(`#${formName} input`);
let object = {};
allInput.forEach(item => {
object[item.name] = item.type === 'radio' ? true : item.checked;
});
localStorage.setItem(formName, JSON.stringify(object));
}
checkChecked(formName) {
const data = JSON.parse(localStorage.getItem(formName));
if (data) {
let i = 1;
for (let [key, value] of Object.entries(data)) {
const item = document.querySelector(`#${formName} input[name='${key}']`);
setTimeout(() => {
if (value) {
item.click();
}
}, i * 1000);
i++;
}
}
}
removeAllChecked(formName, id) {
if (id) {
let allInput = document.querySelectorAll(`#${formName} .${id}`);
allInput.forEach(item => {
item.checked = false;
});
} else {
const allHidden = document.querySelectorAll(`#${formName} .hidden`);
allHidden.forEach(item => {
item.removeAttribute('style', '');
});
}
}
}
new CheckForm('.form');
**CSS**
.hidden {
display: none;
}
Okay, so I am building a fake dish builder for a restraunt. I have a form that includes everything you need to build it, and the only thing I am having trouble with is the ingredient list. Here is my HTML:
<div class="icheckbox" ng-repeat="ing in ingredientList">
{{ing}}
<input type="checkbox" name="{{ing}}" ng-click="addIngredient(ing)"/>
<input type="number" name="more" ng-model="ings.ing.more" placeholder="price for extra"/>
<input type="number" name="less" ng-model="ings.ing.less" placeholder="price for less/none"/>
</div>
and here is the (relevent) JS:
$scope.ings = {};
$scope.ingredientList = ['lettuce', 'tomatoe', 'steak', 'pulled pork', 'green onion', 'red onion', 'mozarella', 'cheddar', 'bacon bits', 'chicken'];
$scope.addIngredient = function(which){
$scope.ings[which] = which;
}
$scope.makeItem = function(item){
item.ingredients = $scope.ings;
console.log(item);
ItemService.createItem(item)
.then(handleRes, handleRes);
}
As I'm sure you guessed, when I am trying to check a box for a specific ingredient and add the price modifiers for more or less of that specific ingredient, it modifies the price for all ingredients in the list. E.g., I can't have individual modifiers because of the model. I know this is a problem with the model, but how can I rewrite my code to accomplish what I'm doing?
for those reading this after the correct answer has been chosen, see the fiddle located here to see a more accurate HTML of what I was working with. By the way, the fiddle doesn't entirely work (for reasons I don't know, but I rarely use JSFiddle), but it is super easy to understand what I was trying to do if you see it I think. http://jsfiddle.net/Lrpjwyrg/13/
i a bit change your fiddle:
first, use ng-model="ings[ing].more" and ng-model="ings[ing].less".
second, save object in ings array instead of just string
$scope.addIngredient = function(which) {
$scope.ings[which] = {
name: which
};
}
angular.module('CpCtrl', []).controller('ControlPanelCtrl', [
'$scope',
function($scope) {
$scope.message = '';
$scope.inglist = ['lettuce', 'tomatoe', 'steak', 'pulled pork', 'green onion', 'red onion', 'mozarella', 'cheddar', 'bacon bits', 'chicken'];
$scope.sauceList = ['bbq', 'ranch', 'nacho cheese', 'yum sauce'];
$scope.ings = {};
$scope.addIngredient = function(which) {
$scope.ings[which] = {
name: which
};
}
$scope.makeItem = function(item) {
item.ingredients = $scope.ings;
console.log(item);
}
}
]);
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="container-fluid text-center" ng-app="CpCtrl" ng-controller="ControlPanelCtrl">
<div class="row">
<div class="page-title text-center">
<h3> Welcome</h3>
</div>
</div>
<div class="row">
<div class="jumbotron">
<h2> Make Item </h2>
<form>
<div class="form-group">
<label for="itemname">Item Name</label>
<input class="form-control" type="text" ng-model="item.itemname" id="itemname" />
</div>
<div class="form-group">
<label for="itemdescription">Item Description</label>
<textarea class="form-control" ng-model="item.itemdescription" id="itemdescription"></textarea>
</div>
<!-- pizza, sub or spud -->
<label>
<div class="icheckbox_square-green">
<input type="checkbox" name="pizza" ng-model="item.pizza" ng-click="setBase()" />Pizza
</div>
</label>
<label>
<div class="icheckbox">
<input type="checkbox" name="sub" ng-model="item.sub" ng-click="setBase()" />Sub
</div>
</label>
<label>
<div class="icheckbox">
<input type="checkbox" name="spud" ng-model="item.spud" ng-click="setBase()" />Spud
</div>
</label>
<!-- end -->
<!-- prices -->
<div class="form-group">
<label for="spud-price" ng-if="item.spud">Spud Price</label>
<input class="form-control" type="number" name="spud-price" ng-if="item.spud" id="spud-price" ng-model="item.price.spud" />
</div>
<div class="form-group">
<label for="pizza-price" ng-if="item.pizza">Pizza Price</label>
<input class="form-control" type="number" name="pizza-price" ng-if="item.pizza" ng-model="item.price.pizza" />
</div>
<div class="form-group">
<label for="sub-price" ng-if="item.sub">Sub Price</label>
<input class="form-control" type="number" name="sub-price" ng-if="item.sub" ng-model="item.price.sub" />
</div>
<!-- end -->
<!-- ingredients -->
<div ng-repeat="ing in inglist">
{{ing}}
<input type="checkbox" name="{{ing}}" ng-click="addIngredient(ing)" />
<input type="number" name="more" ng-model="ings[ing].more" placeholder="price for extra" />
<input type="number" name="less" ng-model="ings[ing].less" placeholder="price for less/none" />
</div>
<!-- end -->
<!-- picture -->
<div class="form-group">
<label for="picture">Add Picture(s)</label>
<input type="file" name="picture" />
</div>
<!-- end -->
<a class="btn btn-primary" ng-click="makeItem(item)">Create</a>
</form>
</div>
</div>
<!-- end item creation -->
I don't know if this is the right answer. But i think it is close to what you want.
angular.module('app', [])
.controller('cntrl', function ($scope) {
$scope.ingredientList = [{
name: 'lettuce',
count: 0,
price: 23,
selected: false
}, {
name: 'tomatoe',
count: 0,
price: 87,
selected: false
}, {
name: 'steak',
count: 0,
price: 98,
selected: false
}, {
name: 'pulled pork',
count: 0,
price: 292,
selected: false
}];
$scope.setItOne = function (idx) {
if ($scope.ingredientList[idx].count < 1) {
$scope.ingredientList[idx].count = 1;
}
updateSelectedingredients();
};
function updateSelectedingredients() {
$scope.selectedingredients = $scope.ingredientList.filter(function (item) {
return item.selected;
});
}
$scope.getTotal = function(){
var total = 0;
( $scope.selectedingredients || []).forEach(function(item){
total = total + item.count * item.price;
});
return total;
};
$scope.makeItem = function () {
alert(JSON.stringify($scope.selectedingredients));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="cntrl">
<div class="icheckbox" ng-repeat="ing in ingredientList">{{ing.name}}
<input type="checkbox" name="{{ing}}" ng-model="ing.selected" ng-change="setItOne($index)" />
<button ng-click="ing.count = ing.count + 1">Up</button>
<button ng-click="ing.count = ing.count - 1" ng-disabled="ing.count < 1">Down</button>
| {{ing.count}} x {{ing.price | currency}} = {{ing.count * ing.price | currency}}
</div>
<hr/>
<div>Selected items
<ul>
<li ng-repeat="item in selectedingredients">{{item.name }} x {{item.count}} -> {{item.count}} x {{item.price | currency}} = {{item.count * item.price| currency}}</li>
</ul>
<b>Total: {{ getTotal() | currency}}</b>
</div>
<button ng-click="makeItem()">Make Item</button>
</div>
</div>
I have a problem with jquery here.
I am running a ajax call to return an SQL query. It basically displays a list of properties, each property has a class name consisting of the development name, the number of bedrooms and whether or not it is a match or nomatch depending on wether or not is matches the checkbox value.
Upon each checkbox click the divs are hidden if they do not match the required parameter.
Working Demo: http://jsfiddle.net/cactuscreative/2PM8H/4/
jQuery
$(function() {
$('#slider-range').slider({
range: true,
min: 0,
max: 700000,
step: 5000,
values: [ 25000, 550000 ],
slide: function(event, ui) {
$( "#price_range" ).val( "£" + ui.values[ 0 ] + " - £" + ui.values[ 1 ] );
},
stop: function(event, ui) {
mi = ui.values[ 0 ];
mx = ui.values[ 1 ];
filterSystem(mi, mx);
}
});
$( "#price_range" ).val( "£" + $( "#slider-range" ).slider( "values", 0 ) + " - £" + $( "#slider-range" ).slider( "values", 1 ) );
});
function filterSystem(minPrice, maxPrice) {
$("div.plotresult").filter(function() {
var price = parseInt($(this).data("price"));
if (isNaN(price)) { price = '0'; }
console.log(price);
$("div.plotresult").hide();
$("div.plotresult").removeClass('match').addClass('nomatch');
return price > minPrice && price < maxPrice;
}).show();
}
$(".filter:checkbox").bind('change',function () {
$("div.plotresult").hide();
$("div.plotresult").removeClass('match').addClass('nomatch');
$("div#overlay").show();
var locationArray = [];
var bedroomArray = [];
var location_Count = 0, bedroom_Count = 0;
$("#location :checkbox:checked").each(function () {
locationArray[location_Count] = $(this).val();
location_Count++
});
$("#bedroom :checkbox:checked").each(function () {
bedroomArray[bedroom_Count] = $(this).val();
bedroom_Count++
});
var locationstring
var bedroonstring
var locationchecked = false
var bedroomchecked = false
if (bedroom_Count == 0) { bedroom_Count = 1; } else { bedroomchecked = true; }
if (location_Count == 0) { location_Count = 1; } else { locationchecked = true; }
for (f2 = 0; f2 < location_Count; f2++) {
if (locationArray[f2] != null) { locationstring = '.' + locationArray[f2] } else { locationstring = '' }
}
for (f3 = 0; f3 < bedroom_Count; f3++) {
if (bedroomArray[f3] != null) { bedroomstring = '.' + bedroomArray[f3] } else { bedroomstring = '' }
}
var QueryString = locationstring + bedroomstring
$(QueryString).removeClass('nomatch').addClass('match').fadeIn('slow');
if (!locationchecked && !bedroomchecked) {
$("div.plotresult").removeClass('nomatch').addClass('match').fadeIn('slow');
};
var mycount = $('.match').length;
$(".totalRes").text(mycount);
});
$('a.showall').click(function () {
$("div.plotresult").removeClass('nomatch').addClass('match').fadeIn('slow');
$("#price :checkbox").removeAttr('checked');
$("#location :checkbox").removeAttr('checked');
$("#price :checkbox").removeAttr('checked');
var mycount = $('.match').length;
$(".totalRes").text(mycount);
return false;
});
Filters
<div class="searchfields">
<div class="wrapper">
<div id="filters">
<div class="locations" id="location">
<h3>Location</h3>
<div class="cumboptions checks">
<p><input type="checkbox" id="cumbria" /> <label><strong>Cumbria</strong></label></p>
<p><input type="checkbox" class="filter" name="location" id="CumbridgeDrive" value="cambridgedrive" /> <label>Cambridge Drive, Penrith</label></p>
<p><input type="checkbox" class="filter" name="location" id="HawksdalePastures" value="hawksdalepastures" /> <label>Hawksdale Pastures, Dalston</label></p>
<p><input type="checkbox" class="filter" name="location" id="CraggClose" value="craggclose" /> <label>Cragg Close, Kendal</label></p>
<p><input type="checkbox" class="filter" name="location" id="MastersGrange" value="mastersgrange" /> <label>Masters’ Grange, Kirkby Lonsdale</label></p>
<p><input type="checkbox" class="filter" name="location" id="Pengarth" value="pengarth" /> <label>Pengarth, Grange-over-Sands</label></p>
</div>
<div class="yorkoptions checks">
<p><input type="checkbox" id="yorkshire" /> <label><strong>North Yorkshire</strong></label></p>
<p><input type="checkbox" class="filter" name="location" id="ImperialCourt" value="imperialcourt" /> <label>Imperial Court, Ingleton</label></p>
<p><input type="checkbox" class="filter" name="location" id="OldLaundryMews" value="oldlaundrymews" /> <label>Old Laundry Mews, Ingleton</label></p>
</div>
</div>
<div class="rooms" id="bedroom">
<h3>Number of Bedrooms</h3>
<div class="options bedrooms">
<p><input type="checkbox" class="filter" name="bedroom" id="one" value="one" /> <label>1</label></p>
<p><input type="checkbox" class="filter" name="bedroom" id="two" value="two" /> <label>2</label></p>
<p><input type="checkbox" class="filter" name="bedroom" id="three" value="three" /> <label>3</label></p>
<p><input type="checkbox" class="filter" name="bedroom" id="four" value="four" /> <label>4</label></p>
<p><input type="checkbox" class="filter" name="bedroom" id="four" value="five" /> <label>5</label></p>
</div>
</div>
<div class="prices" id="price">
<h3>Price (£)</h3>
<div class="options">
<input type="text" id="price_range" class="price_range" value="" />
<div id="slider-range"></div>
</div>
</div>
<p><a class="showall" href="#">Clear Filters</a></p>
</div>
</div>
</div>
Results:
<div id="result">
<h4 class="countresults"><span class="totalRes">6</span> properties match your result</h4>
<div class="plot plotresult mastersgrange three" data-price="0">
<img src="http://placehold.it/1600x620" width="100%" />
<p class="meta">Masters Grange Plot 26</p>
<h3>3 Bedroom Detached House</h3>
<p class="info"></p>
<ul>
<li class="price">£TBC</li>
<li class="rooms">3 Bedrooms</li>
</ul>
</div>
<div class="plot plotresult cambridgedrive four" data-price="395000">
<img src="http://placehold.it/1600x620" width="100%" />
<p class="meta">Cambridge Drive Plot 34</p>
<h3>4 Bedroom Detached House</h3>
<p class="info"></p>
<ul>
<li class="price">£395000</li>
<li class="rooms">4 Bedrooms</li>
</ul>
</div>
<div class="plot plotresult craggclose two" data-price="250000">
<img src="http://placehold.it/1600x620" width="100%" />
<p class="meta">Cragg Close Plot 18</p>
<h3>2 Bedroom Detached House</h3>
<p class="info"></p>
<ul>
<li class="price">£250000</li>
<li class="rooms">2 Bedrooms</li>
</ul>
</div>
<div class="plot plotresult pengarth three" data-price="0">
<img src="http://placehold.it/1600x620" width="100%" />
<p class="meta">Pengarth Plot 8</p>
<h3>2 Bedroom Detached House</h3>
<p class="info"></p>
<ul>
<li class="price">£TBC</li>
<li class="rooms">3 Bedrooms</li>
</ul>
</div>
<div class="plot plotresult pengarth three" data-price="250000">
<img src="http://placehold.it/1600x620" width="100%" />
<p class="meta">Pengarth Plot 10</p>
<h3>3 Bedroom Detached House</h3>
<p class="info"></p>
<ul>
<li class="price">£250000</li>
<li class="rooms">3 Bedrooms</li>
</ul>
</div>
<div class="plot plotresult hawksdalepastures four" data-price="550000">
<img src="http://placehold.it/1600x620" width="100%" />
<p class="meta">hawksdalepastures Plot 65</p>
<h3>4 Bedroom Detached House</h3>
<p class="info"></p>
<ul>
<li class="price">£550000</li>
<li class="rooms">4 Bedrooms</li>
</ul>
</div>
My issue is that they don't play together.
They work as individual filters but if I want to check a development and bedrooms and then between a price bracket then it ignores the checkbox.
Visa versa - i set a price bracket and its ok, then i check a development and bedrooms and it ignores the price bracket.
Any Help would be amazing...
I've gone for a slightly different approach to how your example worked which simplifies the code a lot.
If you have an object to store the search state then you can just then run a search function every time a checkbox is ticked/unticked and the slider updates. Adding data-location and data-bedrooms attributes to each plot also makes things easier for filtering rather than relying on the class names.
See full working example here:
http://jsfiddle.net/77ZLC/
The general gist of it works like so:
// store search state
var search = {
minPrice: 25000,
maxPrice: 550000,
locations: [],
bedrooms: []
};
/**
* Do a search and update results
*/
function doSearch() {
var numResults = 0;
$('.plotresult').each(function(el) {
$el = $(this);
var location = $el.data('location');
var bedrooms = $el.data('bedrooms');
var price = $el.data('price');
var show = true;
// check locations
if (search.locations.length > 0 && $.inArray(location, search.locations) === -1) {
show = false;
}
// check bedrooms
if (search.bedrooms.length > 0 && $.inArray(bedrooms, search.bedrooms) === -1) {
show = false;
}
// check price
var price = parseInt(price, 10) || 0;
if (price < search.minPrice || price > search.maxPrice) {
show = false;
}
if (show) {
numResults++;
$el.removeClass('nomatch').addClass('match');
}
else {
$el.removeClass('match').addClass('nomatch');
}
});
// show/hide results
$('.match').fadeIn();
$('.nomatch').fadeOut();
// update total
$('.totalRes').text(numResults);
};
Here's one way you could do it. You need to add all of your filters to run in one place so you can pass extra params to an event when you trigger it:
http://jsfiddle.net/ahallicks/2PM8H/8/
In this example I've change your filter function to trigger the change event of a checkbox and therefore run through the currently selected filters adding my own at the end:
function filterSystem(minPrice, maxPrice) {
$(".filter:checkbox").trigger("change", [minPrice,maxPrice]);
}
There's a bit of a bug with the fading in then out again, but I'll let you handle that one ;-)