Detecting an html attribute's value with a userscript? - javascript

I am trying to make myself a personal user script, but I need to detect an html attribute's value. For example:
<div id="a">Stuff</div>
<div id="b" value="false"></div>
How could I create an if statement in the script, that triggers if the "value" attribute of element b turns to true?

element = document.getElementById("b");
if(element != null) {
if (element.value == "true") {
// do something
}
}

Check out this link... it says that you can import JQuery into your userscript.
youtube video
You can then get the value of any attrubute using jquery API for attr
Jquery Api attr
which can be done like
var bAttrValue = $("#b").attr("value");
You then coulld write a function which takes in an Id and an attribute like
function GetAttributeValue(elemId, attribute)
{
//Todo: write checks to ensure the elemId exists and that it as the attribute;
var elemAttrValue = $("#"+elemId).attr(attribute);
return elemAttrValue;
}
You could then consume it like
var DivbValue = GetAttributeValue("b", "value")
if(DivbValue) //true
{
//do something
}
else //false
{
//do something
}
alternatively write this in JavaScript
function GetAttributeValue(elemId, attribute)
{
//Todo: write checks to ensure the elemId exists and that it as the attribute;
element = document.getElementById(elemId);
return element[attribute];
}

Related

JavaScript Function Only Working Sometimes With Same Input

I've got the following bit of code (using JQuery) that I've written for a project. The idea is to have a function that you can attach to an element within an "item" div and it will return the id of that div. In this case, the div id would be item-[some item primary key value]. This function works probably 9/10 times, but every once in a while it will get to the else else case and return false. I've verified through the console that the input for selector is the exact same JQuery $() item in both the success and fail cases.
I'm relatively new to JavaScript, so there may be something obvious I'm missing, but this is some really unusual behavior.
var recursionCounter = 0;
function getElementID(selector, recursionDepth, searchString){
console.log(selector);
var elementID = selector.attr("id");
if(elementID === undefined){
elementID = "";
}
if(elementID.indexOf(searchString) !== -1){
elementID = elementID.split("-")[1];
return elementID;
} else {
if(recursionCounter < recursionDepth){
recursionCounter++;
return getElementID(selector.parent(), recursionDepth, searchString);
} else {
recursionCounter = 0;
alert("The element clicked does not have an associated key.");
return false;
}
}
}
Here is an example of code that calls this function, for some context.
$(document).on("click", ".edit-pencil-item", function(event) {
//Use helper function to get the id of the surrounding div then pass it to the function
var itemID = getElementID($(this), 10, "item-");
jsEditItem(itemID);
return false;
});
Thanks in advance for any help!
If you want to get the encapsulating element of your clicked element, and you know it should have an id starting with "item-" you should be able to do something along the lines of
$(this).closest('[id^="item-"]').attr('id')
Which says find this elements closest parent that has an id starting with "item-" and tell me its id.

JavaScript 'function undefined' error working with jsfiddle

I'm trying just to understand an error completely because sometimes I can get around it and other times I can't. I've tried just writing a function:
function toggleButton() {
}
But I get the same error. This is the .js sample.
var checkBox = document.getElementById("chkMyBox");
checkBox.onclick = function toggleButton(e, obj1)
{
var btnElement = document.getElementById("btnMyButton");
if(btnElement != null) {
alert("Element not null");
if(e.target.checked && obj1 != null) {
alert("Checking check " + obj1.checked);
if(obj1.checked == true && btnElement.getAttribute('disabled') == false){
btnElement.getAttribute('disabled') = false;
} else {
btnElement.getAttribute('disabled') = true;
}
}
}
}
Here's the html:
<form id="frmCheckBox">
<input type="checkbox" id="chkMyBox" />
<button id="btnMyButton" disabled>I'm a Button</button>
</form>
http://jsfiddle.net/Arandolph0/h8Re6/3/
Change this line which uses name:
<input type="checkbox" name="chkMyBox" />
into using id instead:
<input type="checkbox" id="chkMyBox" />
Alternatively you could use:
var elements = document.getElementsByName('chkMyBox');
var element = elements[0]; //first element with that name in the array
or
var element = document.getElementsByName('chkMyBox')[0];
Update (as OP changed the code from the original question):
function toggleButton(e, obj1)
This won't work as there is only a single argument given to the callback function (e).
Use e.target to get the element.
You're trying to get an element by its name. You'd have to do:
var checkBox = document.getElementsByName('chkMyBox')[0];
Or, if you prefer by id. Just add id="chkMyBox" to your checkbox input.
You have several problems here.
1) You try to get the button by using getElementById but your element has no id. The easiest fix is to fix your markup.
<input type="checkbox" name="chkMyBox" id="chkMyBox" />
2) Your event handler takes two parameters. When attaching the handler via the DOM, only the event gets passed to your handler. Therefore obj1 will always be undefined. You need to get the checkbox element from the e parameter.
checkBox.onclick = function(e) {
var obj1 = e.target;
// rest of handler
}
3) You shouldn't use getAttribute to check for the element being disabled/enabled. It will give you the text value of the attribute which is an empty string. Instead, use the boolean property that the DOM gives you:
// toggle the disabled attribute
obj1.disabled = !obj1.disabled;

Have a better way to hide and show divs with radio checked?

I created this code a few days, but I believe it is possible to improve it, someone could help me create a smarter way?
// Hide registered or customized field if not checked.
function checkUserType(value) {
if (value == 2) {
$('#registered').hide();
$('#customized').show();
} else if (value == 1) {
$('#registered').show();
$('#customized').hide();
}
}
checkUserType($('input:radio[name="jform[place_type]"]:checked').val());
$('#jform_place_type').on('click', function () {
checkUserType($('input:radio[name="jform[place_type]"]:checked').val());
});
Demo: http://jsbin.com/emisat/3
// Hide registered or customized field if not checked.
function checkUserType(value) {
}
var t = function () {
var value = $('input:radio[name="jform[place_type]"]:checked').val();
if (value == 2) {
$('#registered').hide();
$('#customized').show();
} else if (value == 1) {
$('#registered').show();
$('#customized').hide();
}
};
$('#jform_place_type').on('click', t);
You can improve the Jquery (for the performance) by storing the DOM element and cache the rest. This is the maximum stuff you can reach I guess.
function checkUserType(value) {
var r = $("#registered");
var c = $("#customized");
if (value == 2) {
r.hide();
c.show();
} else if (value == 1) {
r.show();
c.hide();
}
}
var func = function () {
checkUserType($('input:radio[name="jform[place_type]"]:checked').val());
};
$('#jform_place_type').on('click', func);
For any further reading check this JQuery Performance
In particular read the third paragraph of the document
Cache jQuery Objects
Get in the habit of saving your jQuery objects to a variable (much like our examples above). For example, never (eeeehhhhver) do this:
$('#traffic_light input.on').bind('click', function(){...});
$('#traffic_light input.on').css('border', '3px dashed yellow');
$('#traffic_light input.on').css('background-color', 'orange');
$('#traffic_light input.on').fadeIn('slow');
Instead, first save the object to a local variable, and continue your operations:
var $active_light = $('#traffic_light input.on');
$active_light.bind('click', function(){...});
$active_light.css('border', '3px dashed yellow');
$active_light.css('background-color', 'orange');
$active_light.fadeIn('slow');
Tip: Since we want to remember that our local variable is a jQuery wrapped set, we are using $ as a prefix. Remember, never repeat a jQuery selection operation more than once in your application.
http://api.jquery.com/toggle/
$('#jform_place_type').on('click', function () {
//show is true if the val() of your jquery selector equals 1
// false if it's not
var show= ($('input:radio[name="jform[place_type]"]:checked')
.val()==1);
//set both divs to visible invisible / show !show(=not show)
// (not show) means that if show=true then !show would be false
$('#registered').toggle(show);
$('#customized').toggle(!show);
});
If you need a selector more than once then cache it I think it's called object caching as Claudio allready mentioned, thats why you see a lot of:
$this=$(this);
$myDivs=$("some selector");
The convention for a variable holding results of jquery function (jquery objects) is that they start with $ but as it is only a variable name you can call it anything you like, the following would work just as well:
me=$(this);
myDivs=$("some selector");

Using jQuery to display input TITLE as VALUE (jsfiddle included)

I am trying to come up with a simple jquery input watermark function. Basically, if the input field has no value, display it's title.
I have come up with the jquery necessary to assign the input's value as it's title, but it does not display on the page as if it was a value that was hand-coded into the form.
How can I get this to display the value when the page loads in the input field for the user to see?
Here's the fiddle: http://jsfiddle.net/mQ3sX/2/
$(document).ready(function() {
$(".wmk").each(function(){
var value = $(this).val();
var title = $(this).attr("title");
if (value == '') {
value = title;
}
$(".result").text(value);
// You can see I can get something else to display the value, but it does
// not display in the actual input field.
});
});
Instead of writing your own, have you considered using a ready-bake version? It's not exactly what you asked for, but these have additional functionality you might like (for instance, behaving like a normal placeholder that auto-hides the placeholder when you start typing).
http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html
http://archive.plugins.jquery.com/project/input-placeholder
Use the below line of code. You need to specify the input element, and update its value. Since your input field has a class called '.wmk', I am using the below code. You can use "id" and use "#" instead of ".". Read more about selectors at http://api.jquery.com/category/selectors/
$(".wmk").val(value);
Updated jsfiddle http://jsfiddle.net/bhatlx/mQ3sX/9/
Update: since you are using 'each' on '.wmk', you can use
$(this).val(value)
I think what you want is this:
$(document).ready(function() {
$(".wmk").each(function(){
var value = $(this).val();
var title = $(this).attr("title");
if (value == '') {
$(this).val(title);
}
$(".result").text(value);
});
});
May be you want something like below,
DEMO
$(document).ready(function() {
$(".wmk").each (function () {
if (this.value == '') this.value = this.title;
});
$(".wmk").focus(
function () {
if (this.value == this.title) this.value = '';
}
).blur(
function () {
if (this.value == '') this.value = this.title;
}
);
}); // end doc ready

Webkit checkbox default value is null?

When using a WebKit browser (Chrome or Safari), if I try to get the default value of a checkbox, it returns "". However, the same javascript in Firefox or IE will return "on".
So lets say I have this checkbox on a page:
<input type="checkbox" id="chkDefaultValue">
I use this javascript to return all "input" elements on a page
var elems = document.getElementsByTagName('input');
Then I go through a loop that gets the value like this
elems[i].getAttribute('value')
When elems[i] is that checkbox, in Chrome or Safari it returns "", but Firefox or IE it returns "on".
Is there any way to use Javascript to return the "on" value in Safari or Chrome? In Chrome I use a jquery call that uses .val() and that actually returns "on", but I need a way to do this using Javascript in Safari.
Thanks!
EDIT:
I'm actually looking for the "value" attribute specifically since the "value" of a checkbox can be anything, like "cat" or "bike".
Use checked instead to see if a checkbox or radio input is selected.
If what you really want to do is get the value attribute, and not see if the checkbox is selected, then you need to set a value for the checkbox first. If nothing is set then you getting null is the normal behavior.
You can also replicate the Firefox and IE behavior by assigning on yourself as a default value:
var myVal = elems[i].getAttribute('value');
if(myVal === null)
myVal = 'on';
I think that it's because elems[i].getAttribute('value') is not what you should be using to get the state of a checkbox.
Try using elems[i].getAttribute('checked') or just elems[i].checked to get the state.
By the way, elems[i].getAttribute('value') can be shortened to just elems[i].value.
Just read your comment on another answer...
Here's the source for the .val() statement from the jQuery repo:
getVal = function(elem)
{
var type = elem.type, val = elem.value;
if (type === "radio" || type === "checkbox")
{
val = elem.checked;
} else if (type === "select-multiple") {
val = elem.selectedIndex > -1 ? jQuery.map( elem.options, function( elem ) {return elem.selected;}).join("-"):"";
} else if (elem.nodeName.toLowerCase() === "select") {
val = elem.selectedIndex;
}
return val;
}
That is pretty simple JavaScript, and you can just omit the .map() function.
Also, why not just test for the existence of the value property?
function niceValue(element)
{
if (element.value != '')
{
return element.value;
} elseif (element.checked) {
if (element.checked)
{
return 'on';
} else {
return 'off';
}
}
}
Good luck!

Categories