clear the textbox alphabet value after I select the search results - javascript

I have a search engine code in angular2.
when I select the search results I need to display the values in the text box with cross button next to it.
right now I am getting the results.
but when I type alphabet h in the text box, I see some results but when I select hover, the h alphabet not dissapperaing.
to make it disappear I made the text box value as empty but still not working.
providing my code and stack blitz below
can you please help me.
so that in future I can implement myself.
https://stackblitz.com/edit/angular6-fdwnew?file=app/app.component.ts
add(item){
console.log("item--->", item);
this.tags.push(item);
this.value=''
}
delete(item) {
console.log(item);
this.tags = this.tags.filter(x => x !== item)
//this.tags.push(item);
}

You can change the HTML with ngModel which is two way binding in Angular and I feel you better maintain the independent boxes for the Input entry and list of tags
<div contenteditable="true"
class="border"
#textbox
style="border: 2px solid black; min-height:50px; width:300px;"
id="txtDiv"
(keypress)="updateKeyUp($event)"
>
<!---searchTerm$.next($event.target.value)-->
<div>
<span
class="box-tag"
*ngFor="let tag of tags">
{{tag.name}}
<b class="close" (click)="delete(tag)">x</b>
</span>
</div>
</div>
<input [(ngModel)]="nameModel" (keypress)="updateKeyUp($event)" placeholder="Enter Tag Name">{{this.nameModel}}
<ul *ngIf="results">
<li *ngFor="let result of results | slice:0:9" (click)="add(result)">
<a href="{{ result.latest }}" target="_blank">
{{ result.name }}
</a>
</li>
</ul>
Demo Here

Related

How to write step definition file of scenario outline feature in Cypress

I'm using Feature file below:
Scenario Outline: Admin can send invitations to any user roles
And Click on drop-down to select role <Role>
Examples:
|Role|
|Admin|
|Manager|
I'm trying to write a step definition file here, but none of them worked
#1: Passing as parameters... doesn't work
And('Click on drop-down to select role "([^"]*)"', (role) => {
cy.get('.add-person__inputs--container > :nth-child(2) > .ui').contains(role).click()
#2: Passing as string values....doesn't work
And('Click on drop-down to select role {string}', (role_value) => {
cy.get(`.add-person__inputs--container > :nth-child(2) > .ui[value='${role_value}']`).click()
Cypress result of #1 & #2:
#3: also tried this and seems to have a better shot cos simply it gave me a different error LOL
And('Click on drop-down to select role {string}', (role_value) => {
cy.get('.add-person__inputs--container > :nth-child(2) > .ui').find(role_value).click()
Cypress result for #3:
HTML for the page I'm testing, I'm trying to get those highlighted values from dropdown items but it has no id or name in front of each item
And I got cy.get('.add-person__inputs--container > :nth-child(2) > .ui') from Cypress selector
HTML tags
<div class="add-person__inputs--container" style="" xpath="1"><div class="field "><span class="login-form__inputs-container--title">Email</span><div class="ui large input login-form__inputs-container--input"><input name="email" placeholder="Add email address" autocomplete="new-password" type="email" value=""></div></div><div class="add-person__description--container"><span class="login-form__inputs-container--title">Role</span><div name="role" role="listbox" aria-disabled="false" aria-expanded="true" class="ui active visible fluid selection dropdown add-person__dropdown" tabindex="0"><div class="text" role="alert" aria-live="polite">Viewer</div><i aria-hidden="true" class="chevron down icon"></i><div class="visible menu transition"><div role="option" aria-checked="true" aria-selected="true" class="active selected item" style="pointer-events: all;">Viewer</div><div role="option" aria-checked="false" aria-selected="false" class="item" style="pointer-events: all;">Grower</div><div role="option" aria-checked="false" aria-selected="false" class="item" style="pointer-events: all;">Manager</div><div role="option" aria-checked="false" aria-selected="false" class="item" style="pointer-events: all;">Admin</div></div></div></div>
please bear in mind I'm very new to coding but I think the issue is either step definition file or css selector... :(
Thanks in advance :D
It looks in step call missing quotes, try as blow:
And Click on drop-down to select role "<Role>"
In Example: change it to string. This worked for me:
Scenario Outline: Admin can send invitations to any user roles
And click on dropdown to select role.
Examples:
|Role|
|"Admin"|
|"Manager"|
and
('Click on drop-down to select role {string}', (role_value) => {
cy.get(`.add-person__inputs--container > :nth-child(2) > .ui[value='${role_value}']`).click()
So this is what worked for me:
In the feature file:
And Click on drop-down to select role "<Role>"
In the step definition file:
And(/^Click on drop-down to select role "(.*?)"$/, (role) => {
cy.get('.add-person__inputs--container > :nth-child(2) > .ui').contains(role).click()
});

MDC Web: mdc-select update hidden input value on change (non-native select box) | JavaScript (JS)

Been doing well so far with MDC Web Components, but I've been hung up here for far too long. (Not strong in JS.)
mdc-select used to be non-native, then used native HTML select, and now once again it's non-native. For a while MDC Web supported a hidden input so that you could pass values to the server.
There's hardly any documentation - mostly just stuck users like me opening issues on GitHub:
Closed: MDC Select - no longer form input compatible #2221
Closed: [MDC Select] Example in README does send values to the web server #5295
Open: [MDCSelect] Add hidden input element to support HTML forms #5428
I need to set/update the value of a hidden input on MDCSelect change for multiple select boxes on the same page... I can get it to do it for ONE select box, but not multiple.
Here is the select box HTML:
<div class="mdc-select mdc-select--outlined region-select">
<div class="mdc-select__anchor demo-width-class">
<i class="mdc-select__dropdown-icon"></i>
<div id="demo-selected-text" class="mdc-select__selected-text" tabindex="0" aria-disabled="false" aria-expanded="false"></div>
<div class="mdc-notched-outline">
<div class="mdc-notched-outline__leading"></div>
<div class="mdc-notched-outline__notch" style="">
<label id="outlined-label" class="mdc-floating-label" style="">Region</label>
</div>
<div class="mdc-notched-outline__trailing"></div>
</div>
</div>
<div class="mdc-select__menu mdc-menu mdc-menu-surface demo-width-class">
<ul class="mdc-list">
<li data-value="" disabled="" aria-selected="false" role="option" class="mdc-list-item" tabindex="0"></li>
<li data-value="north" aria-selected="false" role="option" class="mdc-list-item" tabindex="-1">North</li>
<li data-value="east" aria-selected="false" role="option" class="mdc-list-item" tabindex="-1">East</li>
<li data-value="south" aria-selected="false" role="option" class="mdc-list-item" tabindex="-1">South</li>
<li data-value="west" aria-selected="false" role="option" class="mdc-list-item" tabindex="-1">West</li>
</ul>
</div>
<!-- THIS IS THE HIDDEN INPUT THANK YOU -->
<input type="hidden" id="name2" name="input_name2" value="" class="my_mdc-select__value" />
</div>
I've tried targeting the hidden input with id, name, and even class. I think I need some sort of integrated function, forEach, or loop - tried adding JS beneath each select with no avail. I've worked the examples (seen below) from other users and no success. JavaScript isn't my thing, I know what it supposed to be happening but don't know the function or loop syntax etc to make this work.
I need to make sure each set/update targets the correct hidden input associated with that particular select box.
Here is my JS that works for ONE select box but not multiple:
// Select Menu
import {MDCSelect} from '#material/select';
const selectElements = [].slice.call(document.querySelectorAll('.mdc-select'));
selectElements.forEach((selectEl) => {
const select = new MDCSelect(selectEl);
select.listen('MDCSelect:change', (el) => {
const elText = el.target.querySelector(`[data-value="${select.value}"]`).innerText;
console.log(`Selected option at index ${select.selectedIndex} with value "${select.value}" with a label of ${elText}`);
// this works but only saves one
document.querySelector('input.my_mdc-select__value').value = select.value;
});
});
Here is some code that others used that I haven't been able to modify/apply (taken from links above):
From nikolov-tmw:
document.querySelectorAll( '[data-mdc-auto-init="MDCSelect"]' ).forEach( function( sel ) {
sel.My_MDCSelect__Value = sel.querySelector('input.my_mdc-select__value');
if ( null !== sel.My_MDCSelect__Value ) {
sel.addEventListener( 'MDCSelect:change', function( a ) {
if ( sel.MDCSelect ) {
sel.My_MDCSelect__Value.value = sel.MDCSelect.value;
}
} );
}
} );
From daniel-dm:
<div class="mdc-select">
...
</div>
<input id="pet-select" type="hidden" name="pets">
<script>
const input = document.querySelector('#pet-select');
const select = document.querySelector('.mdc-select');
select.addEventListener('MDCSelect:change', e => {
input.value = e.detail.value;
});
</script>
Please help! This particular issue has been open since January (people struggling long before) with no clear solution to help non-JS developers implement MDCSelect boxes. Thanks in advance!
The problem is here:
document.querySelector('input.my_mdc-select__value').value = select.value;
Document.querySelector will find the first matching element in the whole document, so in your loop you're always accessing the same input element.
Instead, you should run querySelector method on the parent element of each hidden input, which in your loop will look like:
selectEl.querySelector('input.my_mdc-select__value').value = select.value;

show and hide class based on checkbox value usig Jquery

Hi currently i am developing an filtering application . Please see my html and js code
jQuery(document).ready(function($){
$(".color-label").on("click",function(){
var color_box_val= $(this).find('.color-box').val();
$('.test-li').hide();
$('div:contains('+color_box_val+')').closest('.test-li').show();
});
});
.hidden-color{
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<label class="color-label">Red<input type="checkbox" class="color-box" value="red"/></label>
<label class="color-label">Black <input type="checkbox" class="color-box" value="Black"/></label>
<ul>
<li class="test-li">
<div class="test-div">
<p class="hidden-color">red</p>
red poduct
</div>
</li>
<li class="test-li">
<div class="test-div">
<p class="hidden-color">Black</p>
black Product
</div>
</li>
<li class="test-li">
<div class="test-div">
<p class="hidden-color">Blue</p>
blue Product
</div>
</li>
So here what iam doing is when customer click black , then it will show black product . If the customer click both red and black then we need to show both , and if customer didn't tick anything then we need to show all product .
But i stuck in some point . Here how can i show both red and black when the clicked both ? Currently it is showing the result based on newly clicked check box . Also if they untick every thing then i need to show all box . Please suggest .
The first thing I would recommend changing is how you store color data in your list items. Instead of storing them in a hidden paragraph element, why not store them as HTML5 data- attributes?
Once that is done, it is quite simple to do what you intend: which is basically a OR operation, i.e. when red and black are ticked, you want to show items that are red or black.
The logic is as follow:
You listen to the .change() event on all the checkboxes
When this event is fired, you want to collect the values of all these checkboxes, but only if they are checked. This is done by using .filter(':checked') to select for checked checkboxes and .map() to return the array.
Next, you iterate through all the list items. If their data-color values are found in the array, you show them. Otherwise you hide them.
And all this logic is wrapped within a conditional statement that checks if any of the checkboxes are filtered:
If none is checked, we do not want any filtering
If one or more is checked, we perform filtering using the aforementioned filtering logic
Update: I have used .toLowerCase() to convert all your color values to lowercase, since from your question I can see that the values might be optionally capitalised.
See proof-of-concept example below:
jQuery(document).ready(function($) {
// Listen to change event
$('.color-box').change(function() {
// Store checked checkboxes
var $checked = $('.color-box').filter(':checked');
if ($checked.length) {
// Perform filtering if one or more is checked
// Collect ALL values from all .color-box into an array
var colors = $checked.map(function() {
return $(this).val().toLowerCase();
}).get();
// Iterate through each list item and evaluate
$('.test-li').each(function() {
var $t = $(this);
if (colors.indexOf($t.data('color').toLowerCase()) >= 0) {
$t.show();
} else {
$t.hide();
}
});
}
// If nothing is checked, show all list items
else {
$('.test-li').show();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<label class="color-label">Red<input type="checkbox" class="color-box" value="red"/></label>
<label class="color-label">Black <input type="checkbox" class="color-box" value="Black"/></label>
<ul>
<li class="test-li" data-color="red">
<div class="test-div">
red Product
</div>
</li>
<li class="test-li" data-color="black">
<div class="test-div">
black Product
</div>
</li>
<li class="test-li" data-color="blue">
<div class="test-div">
blue Product
</div>
</li>

How to get value from dynamically created hidden field in JQuery?

In my use case, I am trying to get value from dynamically generated hidden field in JQuery. When I click the button for that iteration I should get the value for the hidden field belongs to that iteration. But I am not able to get it. It is giving the value as 'undefined'
HTML:
<div class="comment-list-new" style= "max-height: 660px !important;overflow-y: scroll;">
<h5>Discussion Board</h5>
<ol>
{{ if .ViewData.Questions }}
{{ range .ViewData.Questions }}
<li>
<p id="question_id" class="question_id_val" hidden>{{.QuestionId}}</p>
<div class="q-comment">
<div class="qanda questiondiv" id="questionarea" name="questionarea">
<div>
<div id="topic" class="upvote pull-left">
<a class="upvote"></a>
<span class="count">3</span>
<a class="downvote"></a>
</div>
<div >
<div class="qanda-info">
<h6><p id="quest_title">{{.QuestionTitle}}</p></h6>
</div>
<p id="quest_text">{{.QuestionText}}</p>
</div>
</div >
<div class="qanda-info">
<div class="user-info">
<img src="/resources/img/team-small-2.png" />
</div>
<h6>{{.UserId}}</h6>
<span class="date alt-font sub">{{.DateCreated}}</span>
<a id="answertext" name ="answertext" type="submit" class="link-text answerbutton">Answer</a>
</div>
</div>
</div>
</li><!--end of individual question-->
{{ end }}
{{ end }}
</ol>
</div><!--end of comments list-->
JS:
$('.questiondiv').on('click', '.submitanswerbutton', function() {
console.log("In submit button");
var question_id = $(this).closest('.question_id_val').val();
var answer_text = $('.answertext_val').val();
console.log(question_id);
console.log(answer_text);
$.getJSON("/submitanswer?question_id="+question_id+"&answer="+answer_text, function(data) {
console.log("answer Response"+data);
newQuestion = "<li><div class='q-comment'><div class='qanda' id='questionarea' name='questionarea'><div><div id='topic' class='upvote pull-left'><a class='upvote'></a><span class='count'>0</span><a class='downvote'></a></div><div ><div class='qanda-info'><h6><p id='quest_title'>"+title+"</p></h6></div><p id='quest_text'>"+desc+"</p></div></div ><div class='qanda-info'><div class='user-info'><img src='/resources/img/team-small-2.png' /></div><h6>Chip Mayer</h6><span class='date alt-font sub'>September 17 2014</span><a id='answertext' name ='answertext' type='submit' class='link-text'>Answer</a></div></div></div></li>";
$('ol').append(newQuestion);
});
});
In the above code I am trying to get the value for the hidden field question_id_val.
Could anyone help me with this?
Use closest() to get a reference to the outer container (li) and then use find() method to get the hidden field.
var question_id = $(this).closest('li').find('.question_id_val').val();
val() method works for usually input form fields(textbox,hidden fields etc..) .So you need to make sure your element is a valid form field in your page.
<input type="hidden" id="question_id" class="question_id_val" />
Or if you want to keep your p tag as it is, Use the html() or text() method to get the content of the p tag.
var question_id = $(this).closest('li').find('.question_id_val').text();
Remember, these method returns the text/html of all child content as well. So make sure to use it wisely.
val() should be used primarily in select, textarea and input elements.
For getting the inner text use html() or text()
var question_id = $(this).closest('.question_id_val').html();
or
var question_id = $(this).closest('.question_id_val').text();
If you know a css selector id or class I don't see problem why you can't do something like this:
var question_id = $('#question_id').text();
Or
var question_id = $('.question_id_val').text();

Grabbing number from selected class based on string match

I need to grab the number between [ and ] within the selected class of an li list, and store the number in a variable. I've tried the following, but I'm missing something. I'm not sure of the regex required to look between brackets and grab a string.
Javascript
var assetID = $(".selected:contains('on-air-date').find('[]');
HTML
<ul id="asset-list" class="expandable selectable normal" style="height: 671px;">
<li class="selected">
<div class="thumb">
<a href="/content/assets/750">
<img src="https://www.google.com/images/srpr/logo11w.png">
</a>
</div>
<div class="title">
<div>
<strong>Title of story</strong>
<br>
<span class="on-air-date">
On air: 10/28/14 05:30:00pm
[750]
</span>
<br>
<span class="blue radius label">Staging</span>
<span class="green radius label">Live</span>
</div>
</div>
</li>
<li>
<div class="thumb">
<a href="/content/assets/4200">
<img src="https://www.google.com/images/srpr/logo11w.png">
</a>
</div>
<div class="title">
<div>
<strong>Another story title</strong>
<br>
<span class="on-air-date">
On air: 12/10/14 02:09:18pm
[4200]
</span>
<br>
<span class="blue radius label">type label</span>
</div>
</div>
</li>
<li>
<div class="thumb">
<a href="/content/assets/4201">
<img src="https://www.google.com/images/srpr/logo11w.png">
</a>
</div>
<div class="title">
<div>
<strong>Yet another story title</strong>
<br>
<span class="on-air-date">
On air: 12/10/14 02:09:18pm
[4201]
</span>
<br>
<span class="blue radius label">type label</span>
</div>
</div>
</li>
</ul>
JSFiddle: link
Your current code is invalid, as :contains is used to look for a text value within an element, not a class. You need to use find() and text() to retrieve the value in the element. From there you can use a regular expression to extract the value in the braces. Try this:
var selectedAirDateText = $('.selected').find('.on-air-date').text();
var matches = /\[(.+)\]/gi.exec(selectedAirDateText);
console.log(matches[1]); // = '750'
Example fiddle
A regular expression can help you get the number as follows:
var num = $('.selected span.on-air-date').text().replace(/[^\[]*\[(\d+)\].*/,'$1');
Demo
:contains('on-air-date') not valid, you cannot use contains to access the child elements with the specified class. Also .find('[]') not valid. The following code worked for me:
$('.selected').click(function () {
var assetID = $(this).find('.on-air-date').text().split('[')[1].replace(']', '');
//this first splits the text into two by '['
//then we get the second half by [1]
//finally we remove the last character ']' by using .replace
alert(assetID);
})
Demo: https://jsfiddle.net/k3keq3vL/1/
You'll need to first get the single item you need or run an $.each to get all in the page.
//run the each statement
$(".on-air-date").each(function(index,value) {
//set the string (str) variable to the value's text which is inside the <span>
var str = $(value).text();
// match the string with [ ] with anything inside. and then remove the last ]. Then take the substring of the content after the [
var value = str.match(/\[(.*?)\]/g)[0].replace(/\]/g,'').substring(1,str.length-1));
});
http://jsfiddle.net/k3keq3vL/8/
Open your console to see the list of numbers returned in the console.log of the string match and substring

Categories