If statement does not seem to be working properly - javascript

I am working on a real estate site and would like to have specific pages to show properties for rent/sale. I am trying to only show properties that have the "Rent" status, but the if statement seems to just default to else.
Using border styles to visibly see if statements.
web page: http://targetrealtygroupdev.com/rent/
What am I missing?
<div class="property-item">
<div class="proprty-inner>
<div class="property-status-bg">
"Rent"
</div>
</div>
</div>
.one {
border: 1px solid red;
}
.two {
border: 1px solid blue;
}
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var status = document.getElementsByClassName("property-status-bg");
for (item of status) {
var type = item.innerText;
if (type == 'Rent') {
jQuery('.property-item').addClass('one');
} else {
jQuery('.property-item').addClass('two');
}
}
});
</script>

you are changing all jQuery('.property-item') for each item
and .property-status-bg is not only with a simple text == 'Rent' or 'Sale' ...
it's look like:
<p>
<span class="property-status-bg" style="background-color: #888">
Rent
<span class="property-arrow" style="border-left-color: #888; border-right-color: #888"></span>
</span>
</p>
So you have to use the string.include method
try:
document.addEventListener("DOMContentLoaded", function(event)
{
document.querySelectorAll('.property-status-bg').forEach(item =>
{
let ClassChoice = item.textContent.includes('Rent') ? 'one' : 'two'
item.closest('.property-item').classList.add( ClassChoice )
})
})

You are selecting all the elements, you are not selecting the one you are referencing in the loop.
item.closest('.property-item').classList.add('one');

Related

How can I handle events in datalist options in vuejs?

I have a requirement where I have to suggest in the data list and when a user selects any of the datalist options, I have to update other input fields accordingly.
Here is my input field and Datalist code.
<input type="text" v-model="party.name" class="form-control form-control-sm shadow-sm" #input="searchPartyByName()" placeholder="Party name" list="queriedParties"/>
<datalist id="queriedParties">
<option v-for="party in queriedParties">{{party.name}}</option>
</datalist>
Now, what I want is, When a user hits enter or click on specific data list option, I want to update my this input field (Which is by default with data list) but I also want to set other form fields.
I have bound other form fields with my party data object. So, Only if I can update my party data object by any event on datalist option, I will be happy! I want something like this.
<option v-for="party in queriedParties" #click="setParty(party)">{{party.name}}</option>
I already tried the above-given example but it's not working. I also tried with #change but it's not working too!
Is there any way to accomplish this? I checked almost all the articles, jsfiddles and codepens available but none of them solves my issue.
datalist doesn't have events but the input does. You should do the following:
<template>
<input type="text" v-model="party.name" .... />
<datalist id="queriedParties">
<option v-for="party in queriedParties">{{party.name}}</option>
</datalist>
</template>
<script>
export default {
watch: {
party: {
deep: true,
handler (old_party, new_party) {
if (old_party.name !== new_party.name) this.searchPartyByName(new_party.name)
}
}
}
</script>
It seems that your queriedParties is an array of objects. Does it work if you have just an array of strings?
For objects use something along these lines:
<template>
<div class="sourceselection">
<div>
<div class="jumbotron">
<h2><span class="glyphicon glyphicon-list-alt"></span> News List</h2>
<h4>Select News Source</h4>
<input v-model="source" list="newssources-list" v-on:input="sourceChanged"
name="source-selection" id="source-selection" class="form-control"
placeholder="Please specify news source ..."/>
<datalist id="newssources-list">
<option v-for="source in sources" v-bind:value="source.name" v-bind:label="source.name"></option>
</datalist>
<div v-if="deepSource">
<h6>{{deepSource.description}}</h6>
<a v-bind:href="deepSource.url" class="btn btn-primary" target="_blank">Go To {{deepSource.name}} Website</a>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'sourceselection',
data () {
return {
sources: [],
source: '',
deepSource: ''
}
},
methods: {
sourceChanged: function(e) {
console.log("source = "+this.source+" new value = "+e.target.value);
var newSource = e.target.value;
// only action if value is different from current deepSource
if (newSource!= this.deepSource.name) {
for (var i=0; i<this.sources.length; i++) {
if (this.sources[i].name == newSource) {
this.deepSource = this.sources[i];
this.source = this.deepSource.name;
}
}
this.$emit('sourceChanged', this.deepSource.id);
}
}
},
created: function () {
var api = "https://newsapi.org/v1/sources?language=en";
this.axios.get(api).then((response) => {
this.sources = response.data.sources;
});
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
There is no event in datalist, so you can't handle, you'd better write your own list. Here is a example open in codepen:
//pug
#app
.form-group.has-feedback
input.input-search.form-control(type='text', v-model='word', placeholder='Search')
ul#list(v-if='Object.keys(filtered_projects).length > 0')
li(v-for='(value, key) in filtered_projects', #click='gotoProjectPage(key)')
span {{value}}
p {{key}}
span.glyphicon.glyphicon-search.form-control-feedback
/*css*/
body {
margin: 10px;
}
#app {
width: 400px;
}
#list {
font-size: 12px;
list-style: none;
margin: 0;
padding: 5px 0;
background-color: white;
border-radius: 0 0 5px 5px;
border: 1px #ccc solid;
}
#list li {
display: block;
padding: 5px 15px;
}
#list li:hover {
background-color: #ccc;
}
#list li span {
font-weight: 550;
}
#list li p {
margin: 5px 0 0;
}
//js
var app = new Vue({
el: '#app',
data: {
word: '',
projects: {"DataCenterMetro":"TEST1","IFF_Handway":"国际香料","SPH_Handway":"上药控股广东有限公司空调系统","QingTang_GZ":"广州地铁_清塘站","BTE_Handway":"白天鹅宾馆","NSSC_SZ":"深圳地铁_南山书城站","TA0301_Handway":"天安云谷二期"}
},
computed: {
filtered_projects: function () {
var vm = this, result = {};
if (vm.word) {
for(var key in vm.projects) {
if(key.toLowerCase().indexOf(vm.word) != -1 || vm.projects[key].toLowerCase().indexOf(vm.word) != -1)
result[key] = vm.projects[key];
}
}
return result;
}
},
created: function () {
var vm = this;
//TODO get projects
},
methods: {
gotoProjectPage: function (key) {
console.log('/map_login?project=' + key);
//TODO handle
}
},
});

Get and put paramter to url based on slected data using jQuery

I have a following <div> structure:
<div class="color-class" data-color="red">
<div class="inside-color">Red</div>
</div>
<div class="color-class" data-color="green">
<div class="inside-color">Green</div>
</div>
<div class="color-class" data-color="blue">
<div class="inside-color">Blue</div>
</div>
So, when people click on any color class then the page is redirected with corresponding color in the url with the following:
var color=urlObj.searchParams.get("color");
$(".color-class").on("click",function(){
if( $(this).find(".inside-color").hasClass("selected")){
location.href=location.href.replace(/&?color=([^&]$|[^&]*)/i, "");
}
else {
var se_val=$(this).data("color");
$(this).find(".inside-color").addClass("selected");
if ( !color ){
if(url.indexOf("?") >= 0){
url =url+"&color="+se_val;
}
else {
url =url+"?color="+se_val;
}
window.location.href=url;
return;
}
if ( color){
urlObj.searchParams.set("color", color+","+se_val);
window.location.href=urlObj;
return;
}
}
});
So using this code i can redirect so after my redirection i get url like example.com/?color=red
Then I have to add class name called selected to the corresponding inside-color.
So I write the following code:
if ( color ){
$(".color-class[data-color='"+color+"']").find(".inside-color").addClass("selected");
}
But if my url is http://www.example.com/?color=red%2Cgreen how i can add selected class to both… ie add selected class to both red and green,
If my url is http://www.example.com/?color=red%2Cgreen and some one again click on green color then how can i remove green from the url and add selected to red color only.
Any Help will be appreciated.
Consider if this was a form, you might have something like:
<form action="example.com" method="get">
<input type="checkbox" class="inside-color" name="inside-color[]" value="red" /><label>Red</label>
<input type="checkbox" class="inside-color" name="inside-color[]" value="green" /><label>Green</label>
<input type="checkbox" class="inside-color" name="inside-color[]" value="blue" /><label>Blue</label>
<button type="submit">Go</button>
</form>
This will create an encoded URL like:
example.com?inside-color%5B%5D=red&inside-color%5B%5D=green
This is the method for passing an Array via GET. one option would be to pass the details in this method and parse it. Doing this will result in a small array and you can then iterate the array set selected on each of the specific colors.
In your example, you are passing a single string in one variable, and using a delimiter. Sp you'd need to first get the string and then split it. Again, this will result in an array that can be iterated.
if the user unchecked one of the options, removing selected, you could then remove that element from the array.
My suggestions:
function setSelections(c) {
$.each(c, function(k, v) {
if (v) {
$(".color-class[data-color=" + k + "]").addClass("selected");
}
});
}
$(function() {
var colors = {
red: 0,
green: 0,
blue: 0
};
$(".color-class").click(function() {
if ($(this).hasClass("selected")) {
$(this).removeClass("selected");
colors[$(this).attr("data-color")] = 0;
} else {
$(this).addClass("selected");
colors[$(this).attr("data-color")] = 1;
}
});
$("#save-selection").click(function(e) {
e.preventDefault();
var url = "http://example.com/?" + $.param(colors);
console.log("URL: " + url);
})
});
.color-class {
width: 40px;
height: 40px;
border: 2px solid #ccc;
border-radius: 4px;
margin: 2px;
}
.color-class:hover {
border-color: #a0a0a0;
}
.color-class.selected {
border-color: #202020;
}
.color-class .inside-color {
border-radius: 3px;
width: 100%;
height: 70%;
color: white;
font-size: 75%;
text-align: center;
padding-top: 30%;
}
.color-class .inside-color.red {
background: red;
}
.color-class .inside-color.green {
background: green;
}
.color-class .inside-color.blue {
background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="color-class" data-color="red">
<div class="inside-color red">Red</div>
</div>
<div class="color-class" data-color="green">
<div class="inside-color green">Green</div>
</div>
<div class="color-class" data-color="blue">
<div class="inside-color blue">Blue</div>
</div>
<button id="save-selection">Save</button>
The console shows: URL: http://example.com/?red=1&green=1&blue=0 This will be easier to parse back into an object that can be used with setSelections() function.
Hope that helps.
ok try something like this i am just posting some part of your code
var color=urlObj.searchParams.get("color");
if ( color ){
var splitColors = color.split('%2C');
for(var i=0;i<splitColors.length;++i)
{
$(".color-class[data-color='"+splitColors[i]+"']").find(".inside-color").toggleClass("selected");
}
}

Remove (and Add) Classes to HTML Element with jQuery, While Updating the DOM tree

I'm trying to change a div's attribute class. I have three defined classes and want to cycle through the classes when a user initiates a click event. The first click event works as expected, but the second doesn't show any results.
I've went through a few iterations of trying to get this to work, but have not had any success. I think what's going on is that the DOM tree isn't being updated with the click event, so when the second click event is fired it sees the card-green class, adds the card-yellow class and then exits the branching logic.
$(document).ready(function() {
$('body').on('click', function(event) {
var cardColors = ['card-green', 'card-yellow', 'card-red'];
if ($(event.target.nodeName).attr('class') == 'card-green') {
$(event.target.nodeName).removeClass(event.target.nodeName.className).addClass(cardColors[1]);
} else if ($(this).attr('class') == 'card-yellow') {
$(event.target.nodeName).removeClass(event.target.nodeName.className).addClass(cardColors[2]);
} else {
$(event.target.nodeName).removeClass(event.target.nodeName.className).addClass(cardColors[0]);
}
})
});
Use a switch and toggleClass(). Details are commented in Snippet. No need for an array if you are using a limited number of options. When using $(this) you don't need to keep track of what you clicked (much like event.target except $(this) isn't concerned about events as it is concerned with owner of function.)
SNIPPET
$(document).ready(function() {
$(document).on('click', 'div', function(event) {
/* Determine $(this) class
|| Pass class through the switch
*/
var color = $(this).attr('class');
/* Each part of the switch is a if/else
|| conditional. If the condition isn't
|| met, then it will kick you
|| down to the next conditional and
|| so on, until you reach default or
|| meet a condition in which case the
|| break will kick you out of switch.
|| Each condition has a toggleClass()
|| method to switch colors according
|| to the present class of div
*/
switch (color) {
case 'green':
$(this).toggleClass('green yellow');
break;
case 'yellow':
$(this).toggleClass('yellow red');
break;
case 'red':
$(this).toggleClass('red green');
break;
default:
break;
}
});
});
div {
height: 30px;
width: 50px;
border: 1px solid black;
cursor: pointer;
}
.green {
background: green
}
.red {
background: red;
}
.yellow {
background: yellow
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
This changes the color in order of the cards array when elements within the document body are clicked:
(Very similar to #gyre's answer, only includes the event.target within the code logic, rather than just the body).
var cards = ['card-green', 'card-yellow', 'card-red'];
$('body').on('click', function() {
var elem = event.target,
curClass = $(elem).attr('class'),
i = cards.indexOf($(elem).attr('class'));
$(elem)
.removeClass(curClass)
.addClass(cards[i = (i + 1) % cards.length]);
});
div {
height: 100px;
width: 100px;
display: inline-block;
}
.card-green {
background-color: green;
}
.card-yellow {
background-color: yellow;
}
.card-red {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo" class="card-green"></div>
<div id="bar" class="card-yellow"></div>
<div id="baz" class="card-red"></div>
Use an additional index variable to keep track of the position in the array:
Demo Snippet:
$(document).ready(function() {
var cardColors = ['card-green', 'card-yellow', 'card-red']
var i = 0
$('body').on('click', function() {
$(this)
.removeClass(cardColors[i])
.addClass(cardColors[i = (i + 1) % cardColors.length])
})
})
body {
width: 100vw;
height: 100vh;
margin: 0;
padding: 0;
}
.card-green { background-color: green; }
.card-yellow { background-color: yellow; }
.card-red { background-color: red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The same code is workable just remove nodeName from removeClass(event.target.nodeName.className) instead of this use removeClass(event.target.className).
Try this, Its working for me.
$(document).ready(function() {
$('body').on('click', function(event) {
var cardColors = ['card-green', 'card-yellow', 'card-red'];
alert(event.target.className)
if ($(event.target.nodeName).attr('class') == 'card-green') {
$(event.target.nodeName).removeClass(event.target.className).addClass(cardColors[1]);
} else if ($(this).attr('class') == 'card-yellow') {
$(event.target.nodeName).removeClass(event.target.className).addClass(cardColors[2]);
} else {
$(event.target.nodeName).removeClass(event.target.className).addClass(cardColors[0]);
}
})
});

React app refreshing page for each item deletion

I have a React app here that works in many browsers:
<!DOCTYPE html>
<html>
  
<head>
  <title>React! React! React!</title>
  <script src="https://unpkg.com/react#15.3.2/dist/react.js"></script>
  <script src="https://unpkg.com/react-dom#15.3.2/dist/react-dom.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
  
<style>
body {
padding: 50px;
background-color: #66CCFF;
font-family: sans-serif;
}
.todoListMain .header input {
padding: 10px;
font-size: 16px;
border: 2px solid #FFF;
}
.todoListMain .header button {
padding: 10px;
font-size: 16px;
margin: 10px;
background-color: #0066FF;
color: #FFF;
border: 2px solid #0066FF;
}
.todoListMain .header button:hover {
background-color: #003399;
border: 2px solid #003399;
cursor: pointer;
}
.todoListMain .theList {
list-style: none;
padding-left: 0;
width: 255px;
}
.todoListMain .theList li {
color: #333;
background-color: rgba(255,255,255,.5);
padding: 15px;
margin-bottom: 15px;
border-radius: 5px;
}
  </style>
</head>
  
<body>
  
  <div id="container">
  
  </div>
  
  <script type="text/babel">
    var destination = document.querySelector("#container");
// es6 is working in the browser :)
let y = [1, 3, 6, 15, 39, 88].find(x => x > 39 && x < 90)
var TodoItems = React.createClass({
render: function(){
var todoEntries = this.props.entries;
function createTask(item){
return (
<li key={item.key}>
<span>{item.text}</span>
<a href="" data-id="{item.id}"
className="remove-filter"
onClick={this.props.remove.bind(item)}
>
remove
</a>
</li>
)
}
// var listItems = todoEntries.map(createTask.bind(this));
return (
<ul className="theList">
{this.props.entries.map(createTask.bind(this))}
</ul>
);
}
});
var TodoList = React.createClass({
getInitialState: function(){
return {
items: []
};
},
addItem: function(e) {
var itemArray = this.state.items;
itemArray.push(
{
text: this._inputElement.value,
key: this.state.items.length
}
);
this.setState({
items: itemArray
})
this._inputElement.value = "";
e.preventDefault();
},
// removing items from a list
// https://stackoverflow.com/questions/27817241/how-to-remove-an-item-from-a-list-with-a-click-event-in-reactjs
removeItem: function(item, event){
event.preventDefault();
var items = this.state.items.filter(function(itm){
return item.id !== itm.id;
});
this.setState({ items: items });
},
render: function() {
return (
<div className="todoListMain">
<div className="header">
<form onSubmit={this.addItem}>
<input ref={(a) => this._inputElement = a}
placeholder="enter task" />
<button type="submit">add</button>
</form>
</div>
<TodoItems remove={this.removeItem} entries={this.state.items} />
</div>
);
}
});
    ReactDOM.render(
      <div>
        <TodoList/>
      </div>,
      destination
    );
  </script>
</body>
  
</html>
I have followed how to remove an item from a list with a click event in ReactJS? and it seems to be working, with a few issues.
First, the example references <a href data-..., but this did not work and redirected me to file:///Users/cchilders/tutorials/javascript/react/todo-list/true, where it got true from something it evaluated (true should be the index.html)
Deletion works using href="", but it flashes the page in an ugly manner, and the usual suspects to make an href do nothing don't work...
...if I try href="#" or href="javascript:;" and similar I get
embedded:60 Uncaught TypeError: Cannot read property 'preventDefault' of undefined
Second, I am getting warning
react.js:20478 Warning: bind(): React component methods may only be bound to the component instance. See TodoList
no matter what, for each thing I try.
Third, it is deleting all items in the list on remove, not just 1 item.
How can I make React do this deletion onclick without refreshing the page, and delete 1 item at a time?
There are few things that u need to change, check the jsfiddle for working example, do the changes in ur code accordingly.
*Don't write like this: {this.props.entries.map(createTask.bind(this))}
instead of that just call a method {this.createTask()} from render, that function will return the complete list, n define createTask outside of the render method. like this:
createTask: function(){
return this.props.entries.map(item=>{
return (
<li key={item.key}>
<span>{item.text}</span>
<a href="#" data-id="{item.id}"
className="remove-filter"
onClick={()=>this.props.remove(item)}
>
remove
</a>
</li>
)})
},
*U forgot to give the dead link to href, don't leave it empty define it like this: href="#".
*Don't bind the props remove method with onClick, use it like normal method calling, like this: onClick={()=>this.props.remove(item)}.
Check jsfiddle: https://jsfiddle.net/79eax14s/
Let me know if u need any help in this.

How to use the jQuery Selector in this web application?

I am trying to work out to select a delete icon in my own web application. delectIcon
HTML
<main>
<div class="container">
<div class="tabs">
<p><span class="active">Newest</span></p><a href=""><p>
<span>Oldest</span></p></a><p><span>Add</span></p>
</div>
<div class="content">
<ul>
<li>
<span class="itemLeft">Answer emails</span>
<span class="itemMiddle">12-31-2016</span>
<span class="itemRight">1</span>
<b class="deleteIcon"> X </b>
</li>
<li>
<span class="itemLeft">Prep for Monday's class</span>
<span class="itemMiddle">12-31-2016</span>
<span class="itemRight">5</span>
<b class="deleteIcon"> X </b>
</li>
</ul>
</div>
</div>
</main>
JavaScript
$(".deleteIcon").on("click", function () {
alert("Oh, clicked!");
return false;
});
I failed to do so by writing it myself. So I used Chrome Web Developer Tool to find the CSS path. I tried to use the XPath($"[/html/body/main/div/div[2]/ul/li[ 1 ]/b]") and CSS Path ($"(pathbody > main > div > div.content > ul > li:nth-child(1) > b)"). Neither of them worked.
I tried to mark it with an ID and made only one "li" exists. The CSS selector worked all right. But when I clicked the deleteIcon$"(#deleteIcon)", nothing happened.
#deleteIcon{
float:right;
font-weight: bold;
padding: 0 3px 0 3px;
border-radius: 5px;
background: #ccc;
cursor: pointer;
margin-left: 5px;
font-size: 1.3em;
text-align: center;
}
I also tried to select my title. I found the following worked out.
$(".container h1").on("click", function () {
alert("Oh, no!");
return false;
});
I do not what to do now. Can anyone help me out here?
Thank you! I would be really appreciate if you can answer my question.
Adding more details:
I did actually add the deleteIcon into the HTML by JavaScript. I do not know whether this can have an effect on my selector.
Actual HTML
<main>
<div class="container">
<div class="tabs">
<p><span class="active">Newest</span></p><a href=""><p>
<span>Oldest</span></p></a><p><span>Add</span></p>
</div>
<div class="content">
</div>
</div>
</main>
JavaScript (The important part listed below)
function Item(name,dueDate,type){
this.name=name;//1
this.dueDate=dueDate;//input2
this.type=type;//3
};
$(".tabs a span").toArray().forEach(function (element) {
var $element = $(element);
// create a click handler for this element
$element.on("click", function () {
var $content,
$input,
$button,
i;
if ($element.parent().parent().is(":nth-child(1)")) {
// newest first, so we have to go through
// the array backwards
$content = $("<ul>");
for (i = Task.length-1; i >= 1; i--) {
// $buttondelete = $("<buttonDelete>").text("X");
var txt1 = Task[i].toStringName();
var txt2 = Task[i].toStringDate();
var txt3 = Task[i].toStringType();
//alert(txt3);
$content.append('<li> <span class="itemLeft">'+txt1+'</span> <span class="itemMiddle">'+txt2+'</span> <span class="itemRight">'+txt3+'</span><b class="deleteIcon"> X </b>');
}
}
$("main .content").append($content);
return false;
});
});
If you are creating the items inside ul dynamically you should bind the click event like this :
$(".content").on("click", ".deleteIcon", function()
{
alert("clicked") ;
return false;
}
) ;
The class selector starts with a . (just like the example you say you have that works).
Try
$(".deleteIcon").on("click", function () {
alert("Oh, clicked!");
return false;
});

Categories

Resources