How to click using query selector - javascript

I am having a list of navigation items that on load click the first element from the list
<li class="nav-item" v-for="(checkoutplan, index) in checkoutplans" :key="checkoutplan.id">
<a class="nav-link" :class="{ 'active show' : index === 0 }" href="#settings" data-toggle="tab" #click="editModal(checkoutplan)">Checkout Plan {{index +1}}</a>
</li>
What i am trying
document.querySelector("li[class='nav-item']").click()
nor
document.querySelector("li.nav-item:first-child").click()
It is not working
created() {
axios.get("api/checkoutplan")
.then(({ data }) => {this.checkoutplans = data;document.querySelector("a.nav-link:first-child").click();});
}

First add refs to your HTML (at a tag) as
<li class="nav-item" v-for="(checkoutplan, index) in checkoutplans" :key="checkoutplan.id">
<a :id="'nav' + index" :ref="'nav' + index" class="nav-link" :class="{ 'active show' : index === 0 }" href="#settings" data-toggle="tab" #click="editModal(checkoutplan)">Checkout Plan {{index +1}}</a>
</li>
Now in vuejs
$(this.$refs.nav0).click(function(){
//nav0 is beacuse you want first element & first element index is 0
});

as your comment , I tried like below in mounted method (not created) .Beware nextTick is required when vue element is modify by data
new Vue({
el: "#app",
data: {
checkoutplans : []
},
methods: {
editModal : function(param) {
console.log(param);
}
},
mounted: function() {
this.checkoutplans = [{id:1},{id:2}];
this.$nextTick(() => {
this.$el.querySelector("li.nav-item:first-child a").click();
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<ul>
<li class="nav-item" v-for="(checkoutplan, index) in checkoutplans" :key="checkoutplan.id">
<a class="nav-link" :class="{ 'active show' : index === 0 }" href="#settings" data-toggle="tab" #click="editModal(checkoutplan)">Checkout Plan {{index +1}}</a>
</li>
</ul>
</div>
Your code seem to click first li after api called ! So the method you will call is editModal({firstItem}) . How about calling the method directly without clicking like
axios.get("api/checkoutplan")
.then(({ data }) => {this.checkoutplans = data;this.editModal(this.checkoutplans[0]) // direct call });
Created method is not ready state for document element so you can't call document element in that method

var button = document.querySelector("input[type=button]");
button.addEventListener("click", function() {
alert("button was clicked");
})

document.querySelector('.nav-link');
please try this code.

You binded click event in href a.nav-link tag. not in so try
document.querySelector("a.nav-link:first-child").click()

Related

Replace in variable a href address

I am beginner web developer.
I have small problem with my code:
var nodes = document.querySelectorAll('.breadcrumb-item');
if(nodes != undefined && nodes !=''){
var first = nodes[0];
console.log('xxxxxx' , first);
}
It's return me:
[Log] xxxxxx
<li role="presentation" class="breadcrumb-item">
Home
</li>
I need check:
if a href is "Home" then replace href from "#/" to "/dashboard"
if a href is not "Home" then show console.log('not find').
How can I make it?
I have dynamic string. For example:
<li role="presentation" class="breadcrumb-item">
Home
</li>
<li role="presentation" class="breadcrumb-item">
Dogs
</li>
<li role="presentation" class="breadcrumb-item">
calls
</li>
<li role="presentation" class="breadcrumb-item">
cats
</li>
I need replace URL ONLY for Home
I've written assuming that Home will always be first in order. If you're going to change its order, you'll will have to change the index for nodes inside if block.
const nodes = document.querySelectorAll(".breadcrumb-item");
if (nodes.length > 0) {
const first = nodes[0].firstElementChild;
first.href = "/dashboard";
console.log(first);
}
Previous answer is correct. Maybe the following gives you a clearer understanding:
const nodes = document.querySelectorAll('.breadcrumb-item');
if (nodes.length > 0) {
const first = nodes[0].firstElementChild;
let currentUrlTitle = first.text.trim().toLowerCase();
if (currentUrlTitle == 'home') {
console.log(first.text);
first.href = '/dashboard';
console.log(first.href);
} else {
console.log(currentUrlTitle);
}
}

Add style to specific element angular 6

I have the following block of code in the front-end:
<li *ngFor = "let cat of this.dataCategory.iconTitleSet" (click)="getTypeFromCategory(cat.title)" class="list-group-item puntero">
<img [src]="cat.icon" alt="icon" title="icon" />{{cat.title}}
</li>
in the component:
getTypeFromCategory(tipo: string) {
this.typeItem = tipo.toLowerCase();
if (this.arrayTipo.includes(this.typeItem)) {
const i = this.arrayTipo.indexOf( this.typeItem );
this.arrayTipo.splice( i, 1 );
} else {
this.arrayTipo.push(this.typeItem);
}
}
in synthesis what up to now does is add a value that I get from FRONTEND in an array in case it is not, and if it eliminates it from the array, but when I add it I also want to put a specific style, for example a yellow background, but this last I do not know how to do it, I do not know how to say to angular that I put a specific style in element "li" specific generated by an "ngfor" loop when I click on the element.
this is the image in the frontend
You can do it in some ways:
1. to set a diffrennt class with [ngClass]="" to each li and style in css
for example:
<li *ngFor = "let cat of this.dataCategory.iconTitleSet;let i=index;" [ngClass]="'title_'+i" (click)="getTypeFromCategory(cat.title)" class="list-group-item puntero">
<img [src]="cat.icon" alt="icon" title="icon" />{{cat.title}}
</li>
in css:
.title_1{}
2. you can set it with [ngStyle] or style.
<li *ngFor = "let cat of this.dataCategory.iconTitleSet;let i=index;" [style.color]="cat.color" (click)="getTypeFromCategory(cat.title)" class="list-group-item puntero">
<img [src]="cat.icon" alt="icon" title="icon" />{{cat.title}}
</li>
You can do the following.
HTML
<li *ngFor = "let cat of this.dataCategory.iconTitleSet; let i = index" (click)="getTypeFromCategory(cat.title, index)" class="list-group-item puntero" [class.changeColor]="i == selectedValue">
<img [src]="cat.icon" alt="icon" title="icon" />{{cat.title}}
Component
selectedValue: any;
getTypeFromCategory(tipo: string, index) {
this.selectedValue = index;
this.typeItem = tipo.toLowerCase();
if (this.arrayTipo.includes(this.typeItem)) {
const i = this.arrayTipo.indexOf( this.typeItem );
this.arrayTipo.splice( i, 1 );
} else {
this.arrayTipo.push(this.typeItem);
}
}
class changeColor will be applied to every list item selected.

ng-Include: evaluator function never called

HTML:
<section ng-controller="NavigationController as navCtrl">
<ul>
<li ng-click="navCtrl.setNav(1)" ng-class="{ 'myApp_nav_items_selected': navCtrl.isNavPage(1) , 'myApp_nav_items': !navCtrl.isNavPage(1) }"><a ng-class="{ 'myApp_nav_selected_a': navCtrl.isNavPage(1) , 'myApp_nav_a': !navCtrl.isNavPage(1) }" href="#">Option 1</a></li>
<li ng-click="navCtrl.setNav(2)" ng-class="{ 'myApp_nav_items_selected': navCtrl.isNavPage(2) , 'myApp_nav_items': !navCtrl.isNavPage(2) }"><a ng-class="{ 'myApp_nav_selected_a': navCtrl.isNavPage(2) , 'myApp_nav_a': !navCtrl.isNavPage(2) }" href="#">Option 2</a></li>
<li ng-click="navCtrl.setNav(3)" ng-class="{ 'myApp_nav_items_selected': navCtrl.isNavPage(3) , 'myApp_nav_items': !navCtrl.isNavPage(3) }"><a ng-class="{ 'myApp_nav_selected_a': navCtrl.isNavPage(3) , 'myApp_nav_a': !navCtrl.isNavPage(3) }" href="#">Option 3</a></li>
</ul>
<div class="myAppta_page">
<div ng-include="navCtrl.getPage()"></div>
</div>
</section>
JS
tripdataApp.controller('NavigationController', function ($scope) {
this.$scope = $scope;
this.$scope.navPage =1;
this.setNav = function(theNavPage) { <--- WORKS OK
console.log("set nav " + theNavPage);
this.$scope.navPage = theNavPage;
console.log("nav IS set to " + this.$scope.navPage);
};
this.isNavPage = function(checkNavPage) { <---- WORKS OK
return this.$scope.navPage === checkNavPage;
};
this.getPage = function() { <---- NEVER CALLED
console.log("-=-=-=-=- nav IS set to " + this.$scope.navPage);
switch (this.$scope.navPage)
{
case 1:
console.log("dashboard");
return "#/pages/dashboard.php";
break;
default:
console.log("ddefault");
return "#/pages/unimplemented.php";
break;
}
}
});
What am I doing wrong?
As per I can see in the docs, there is no reference saying that you can evaluate a controller method within an ng-include directive. Other than that, it does say that you can use a constant but you have to add single quotes wrapping up the content of the ng-include.
For more info https://docs.angularjs.org/api/ng/directive/ngInclude
I think a different approach is the solution for this issue.

data-id attribute using jquery?

I'm using jQuery. I need to get the data-id of the clicked item and pass it to a webservice. How do I get the data-id attribute?
My HTML looks like this:
<ul class="nav nav-pills">
<li class="onselectedCategory" data-id="12">12</li>
<li class="onselectedCategory" data-id="23">23</li>
<li class="onselectedCategory" data-id="34">34</li>
<li class="onselectedCategory" data-id="45">45</li>
<li class="onselectedCategory" data-id="56">56</li>
</ul>
And my JavaScript looks like this:
events{
"click li.onselectedCategory": "selectCategory"
}
selectCategory: function(event){
event.preventDefault();
var _selectedValue = $(this).data('id');
alert("Selected Value : "+_selectedValue);
},
Try this:
$(".onselectedCategory").click(function(){
alert($(this).data("id"));
});
onselectedCategory is a class, therefor you need to reference it with a . and not with the # which is used for ids.
change #data-id to data-id
$(".onselectedCategory").click(function(){
alert($(this).attr("data-id"));
})
Edit for backbone
selectCategory: function(event){
event.preventDefault();
var selectedValue = "";
if($(e.target).is('li')) {
selectedValue =$(e.target).attr('data-id');
} else {
selectedValue =$(e.target).parent().attr('data-id');
}
alert("Selected Value : "+ selectedValue);
},
The onselectedCategory class must be within the label <a>
<li><a class="onselectedCategory" data-id="12" bla,bla,bla...</li>
$(".onselectedCategory").click(function(){ alert($(this).data("id")); });

set order to jquery sortable

I use jquery draggble function for unorderd list (ul) and face a problem of getting the order of items after it changed and setting the order ofter page is loaded.Suppose we have the following code :
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js> </script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script>
$(document).ready(function(){
$('.secondblock').sortable({axis:'y'});
$(".block").sortable({
axis: 'y',
update: function(event, ui) {// order changed
var order = jQuery(this).sortable('toArray');
// set this order to .secondblock
}
});
});
</script>
</head>
<body>
<ul class="block" type="none">
<li id = "one">1</li>
<li id = "two">2</li>
<li id = "three">3</li>
<li id = "four">4</li>
<li id = "five">5</li>
</ul>
<ul class="secondblock" type="none">
<li id = "one">1</li>
<li id = "two">2</li>
<li id = "three">3</li>
<li id = "four">4</li>
<li id = "five">5</li>
</ul>
</body>
Are there any possible solutions?
First, you shouldn't have the same id appear twice in a document. That will cause all kinds of problems.
Instead, set a data-attribute on the items in the second list to reflect corresponding items in the first list:
<ul class="block" type="none">
<li id = "one">1</li>
<li id = "two">2</li>
<li id = "three">3</li>
<li id = "four">4</li>
<li id = "five">5</li>
</ul>
<ul class="secondblock" type="none">
<li data-block-id = "one">1</li>
<li data-block-id = "two">2</li>
<li data-block-id = "three">3</li>
<li data-block-id = "four">4</li>
<li data-block-id = "five">5</li>
</ul>
Then reflecting the sort of the first list in the second list is simple:
$('.block').sortable({update: sortOtherList});
function sortOtherList(){
$('.block li').each(function(){
$('.secondblock [data-block-id=' + $(this).attr('id') + ']')
.remove()
.appendTo($('.secondblock'));
});
}
See it working here: http://jsfiddle.net/6HKZG/2/
Faust's looks better to me. Mark it if it's what you wanted.
Yes. I feel like I need more information, but I had to do almost the exact same thing recently.
First, you want to extend the javascript array object with a sorting algorithm. Here is what I use:
Array.prototype.move = function (old_index, new_index) {
if (new_index >= this.length) {
var k = new_index - this.length;
while ((k--) + 1) {
this.push(undefined);
}
}
this.splice(new_index, 0, this.splice(old_index, 1)[0]);
return this; // for testing purposes
};
source Move an array element from one array position to another
Then, what I would do is use this along with an OldPosition/NewPosition function to get the index of the element before and after the sort, and use this method to move the object in the array.
I think JQuery sort let's you get information about the array before and after the sort
ex:
$('li').presort(function() {
window.oldindex = $(this).index();
});
$('li').postsort(function() {
window.newindex = $(this).index();
array.move(oldindex,newindex);
});
If you're just looking to make .secondblock match .block after sort, you can do this:
source: http://jqueryui.com/demos/sortable/#events
$( ".selector" ).sortable({
start: function(event, ui) { //Get the order of the .block list items before dragging }
});
$( ".selector" ).sortable({
stop: function(event, ui) { //Get the new order of the list items after dragging. Compare the two orders and sort .secondblock to match block }
});

Categories

Resources