HTML attribute comparison - javascript

How would you code a if conditional check in dojo?
if(!dojo.query("#idOfHhtmlField").attr("disabled") == true)
{
//do something
}
Here I am trying to compare if #idOfHhtmlField's disabled attribute is set to true or not, but it doesnt seem to be working for me.

i tested this html in dojo,here:
<button id="test0" disabled>button0</button>
<button id="test1" disabled="disabled">button1</button>
<button id="test2" disabled="false">button2</button>
<div id="test3" disabled>div0</div>
<div id="test4" disabled="disabled">div1</div>
<div id="test5" disabled="false">div2</div>
since you can set div's disabled in ie8, so it returns all true.
but in chrome only the buttons return true.
you should check if #idOfHhtmlField is a form element .
update
i suggest you detect disabled this way,because browsers do not need its value:
if(dojo.hasAttr("id",'disabled')){
//alert(123)
}
i know little about dojo , because dojo.query().attr() returns an object,it is weired!
and here is the official guide.

if(!dojo.query("#idOfHhtmlField").disabled) {
...
}

Is idOfHhtmlField a DOM element (div, span, input etc)? or is it a dijit widget?
If it is a DOM node, you might want to use:
var field = dojo.byId('idOfHtmlField');
console.log(field.disabled);
If you are using a dijit widget of some type (either programmatic instantiation or declarative via dojoType or data-dojo-type), you will want to use:
var fieldWidget = dijit.byId('idOfHtmlField');
var isDisabled = fieldWidget.get('disabled');
console.log(isDisabled);

Related

Create a single search box which searches two different sites using javascript

I've made multiple search boxes that search external dictionary sites. Due to the site search syntax, I've had to use JavaScript to construct a url from the text box input. This code works perfectly fine:
function prepare_link_glosbe() {
var url_param_gl = document.getElementById('url_param_gl');
var target_link_gl = document.getElementById('target_link_gl');
if ( ! url_param_gl.value ) {
return false;
}
target_link_gl.href = "https://nb.glosbe.com/en/nb"
target_link_gl.href = target_link_gl.href + '/' + encodeURI(url_param_gl.value);
window.open(target_link_gl.href, '_blank')
}
function prepare_link_dict() {
var url_param_dict = document.getElementById('url_param_dict');
var target_link_dict = document.getElementById('target_link_dict');
if ( ! url_param_dict.value ) {
return false;
}
target_link_dict.href = "https://www.dict.com/engelsk-norsk"
target_link_dict.href = target_link_dict.href + '/' + encodeURI(url_param_dict.value);
window.open(target_link_dict.href, '_blank')
}
<!--Search Glosbe.com-->
<div style="border:0px solid black;padding:8px;width:60em;">
<table border="0" cellpadding="2">
<tr><td>
<input type="text" onfocus="this.value=''" value="Search glosbe.com" name="url_param_gl" id="url_param_gl" size="40"/>
<input type="button" onclick="prepare_link_glosbe()" value="Glosbe (en-no)" />
<a href="https://nb.glosbe.com/en/nb" id="target_link_gl" target="_blank" ></a>
</td></tr></table></div>
<!--Search Dict.com-->
<div style="border:0px solid black;padding:8px;width:60em;">
<table border="0" cellpadding="2">
<tr><td>
<input type="text" onfocus="this.value=''" value="Search dict.com" name="url_param_dict" id="url_param_dict" size="40"/>
<input type="button" onclick="prepare_link_dict()" value="Dict (en-no)" />
<a href="https://www.dict.com/engelsk-norsk" id="target_link_dict" target="_blank" ></a>
</td></tr></table></div>
However, I wish to search both sites using a single input box. I've tried different approaches, including addEventListener, but I'm not fluent enough in either HTML or JavaScript to achieve it. Can anyone point me in the right direction?
First of all, some things that will make your life easier in the long run:
You don't need this.value='', just use the placeholder attribute - it's well supported.
Don't use <table> to create a layout.
Don't use attributes to assign JS event handlers. (so no onclick=)
And now, how to use just one text field for both websites - just remove the second field and move the button somewhere else. Here's an example:
// This is our search input field.
const searchValue = document.getElementById('search_value');
// Here I'm looking for all search buttons and iterating over them
// with for ... of, querySelectorAll accepts valid CSS selectors.
for (let button of document.querySelectorAll('.search_button')) {
// Getting the data-url attribute value from the button.
const url = button.dataset.url;
// Adding a click event handler, instead of relying on onclick=''
button.addEventListener('click', function () {
// Quick string replace...
const targetURL = button.dataset.url.replace('%s', encodeURI(searchValue.value));
// ...and here we open the new tab.
window.open(targetURL, '_blank');
});
}
<div>
<input type="text" placeholder="Search..." id="search_value" />
<button class="search_button" data-url="https://nb.glosbe.com/en/nb/%s">Glosbe (en-no)</button>
<button class="search_button" data-url="https://www.dict.com/engelsk-norsk/%s">Dict (en-no)</button>
</div>
Here's the explanation:
I'm using the HTML data-* attributes (accessible in JS via element.dataset.*) to store the URL, %s is being used as a placeholder for the search value and will be later replaced with the .replace function.
Instead of manually assigning IDs to buttons I've declared a class - this allows you to extend the application infinitely.
I've merged the input fields into just one and read its value in the button event handler.
I've replaced your this.value='' hack with a proper placeholder.
I've removed the table layout, if you wish to add a nicer layout or styling I would suggest to learn more about CSS - also: don't use HTML attributes to style elements (except for class and style). Avoid using ID selectors in CSS as well (it's fine in JS, but in CSS it can cause issues when it comes to importance). Also, you should avoid the style attribute anyway - it will take precedence over most CSS rules except for the rules with !important and causes code duplication.

why doesn't element.attribute doesn't work in Edge?

I'm creating a small quiz type application in javascript. My html structure looks like this.
<div class="btn-group-toggle" data-toggle="buttons">
<label class="btn btn-secondary btn-insight" data-target="#myCarousel" data-responseID="1">
<input type="radio" name="options" id="option1" autocomplete="off">
<h5>1</h5>
<p class="mb-0">label for 1</p>
<div class="line-bottom gradient-purple"></div>
</label>
...
</div>
I'm trying to use the custom data attribute data-responseID to determine what answer was provided by the user.
When the program starts, loop through the labels using querySelectorAll and attaching a click listener to each one.
const responseLables = document.querySelectorAll('div.btn-group-toggle > label');
responseLables.forEach(element => {
element.addEventListener('click', function(e){
const clickedResponse = element.attributes[2].value;
determineWhereToSlide(clickedResponse);
});
});
This works well in Firefox and Chrome, but doesn't in Edge. (I'm not concerned with IE 11)
determineWhereToSlide is just a function that gives an alert for now. Eventually it'll be used to push the carousel forward.
I've made a working example and you can see the issue if you open it up in different browser.
https://codepen.io/anon/pen/dLmQKZ?editors=1010
I don't get why this is happening.
*EDIT 1
I just realized that the order of the attributes are different. If you change the index value to ...attributes[1]... then it works just fine. Is there a better way to do this rather than providing an index?
Don't refer to attributes by index (even if it seems it should work, attributes were unordered at least until DOM3). Use any of:
element.getAttributeNode("data-responseID").value
element.attributes["data-responseID"].value
element.getAttribute("data-responseID")
element.dataset.responseID
You can use the getAttribute() method.
replace this
const clickedResponse = element.attributes[2].value;
to this
const clickedResponse = element.getAttribute('data-responseID')

AngularJS / jQuery "parent()" selects different element in FF than in Chrome and Safari, why?

I've found a bizarre quirk in AngularJS/Firefox where the selectors use grab different elements. I've put it in a Plunker to demonstrate it's effect:
http://plnkr.co/edit/H7stCpQE59i0aUlQ865j?p=preview
Open it in Chrome and click the button. You're actually selecting a hidden <input> element, then Angular passes it's event/parent along, grabs the parent <button> and adds the class .active to it, like so:
$scope.selectTag = function($event){
var elem = angular.element($event.srcElement).parent();
if(elem.hasClass('active')){
elem.removeClass( "active" );
}else{
elem.addClass('active');
}
}
In Firefox, though, it selects the <input> element and adds .active to that rather than the <button> that is its parent.
Any ideas on why this is happening?
No need for using jQuery. Just use ng-class. Following requires zero code in controller to accomplish what your code will end up doing. Also controllers shouldn't have any DOM manipulation code in them
<label class="btn btn-default" ng-class="{active:btn_active}" >
<input class="" ng-click="btn_active=!btn_active" type="checkbox" />
Button Text
</label>
Learn to look for angular approaches first before using jQuery methodology!
DEMO
As in the comment by Arun P Johny, use $event.target rather than srcElement. But, you shouldn't be manipulating the DOM like that when using Angular JS. Instead, you could do this with ng-class.
<label class="btn btn-default" ng-class="foo">
<input class="" ng-click="foo=(foo==='active') ? '' : 'active'" type="checkbox" />
Button Text
</label>

How to erase the text input that the user typed using JavaScript

<div class = "search ui-widget">
<label for = "keyword"></label>
<input type="text" id="keyword" onkeypress="searchKeyPress(event)" placeholder="Search here" required>
<input type="button" id="btnSearch" onclick="loadDeals('search', keyword.value,'')" />
</div>
$('.search input#keyword').Value('');
Basically what I want is to remove the user's input in the text box after the user clicks another menu tab. I tried $('.search input#keyword').Value(''); and $('.search input#keyword').css("value", ''); but it didn't work.
.val() is the right name of the jQUery method, not Value().
You can use jQuery like this:
$('#keyword').val('');
Or you can use plain javascript like this:
document.getElementById('keyword').value = '';
If there are more input fields beside the ones you posted and you want to clear all inputs you can use:
$('.search input').val('');
Here's a pure javascript solution:
document.getElementById('keyword').value = '';
Since HTML id attributes are supposed to be unique I would recommend not using the '#keyword' id in your jquery selector. The solution does work if there's only one text field, but it isn't scalable to multiple text fields. Instead, I would make 'keyword' a class for the input element and use the selector:
$('.search input.keyword').val('');
This is very similar to the solution Sergio gave except it allows you to control, via the 'keyword' class, which input elements have their values cleared.
Use this
$("the_class_or_id").val("");
Link for this: jQuery Documentation
This is introduced in jQuery API. You can use .value in JavaScript, but in jQuery its val(). It gets the value of the object and to clear the value, just add quotes!
JavaScript code would be:
document.getElementById("id_name").value = "";

What is this functionality called, and is it in HTML or Javascript?

I'd like to find out how this is commonly implemented, mainly because I can't seem to find it in the source code - it's the "graying out" of text that happens whenever a menu-option/button is unable to be clicked. I'm trying to find it in firebug but this is what I find for the image:
<input
type="submit"
onclick="LoadingMsg();"
class="btnclass"
disabled="disabled"
id="ctl00_ctl00_Content_ContentItems_btnUpdateQuotas1"
value="Update Quotas"
name="ctl00$ctl00$Content$ContentItems$btnUpdateQuotas1"
>
This is what it looks like:
It's HTML but can be implemented using JavaScript to manipulate the HTML input/select element to have that property.
This is the attribute that does it: disabled="disabled"
A basic example of JavaScript manipulating this attribute would be:
document.getElementById('elementid').disabled = true; // Disable element
document.getElementById('elementid').disabled = false; // Enableelement
Resources: disabled attribute

Categories

Resources