javascript trouble with the setattributefunction - javascript

I use a form that display some div depending on which option you click of the radio button.
The thing is that the div is set to be none displayed, except if I select an option.
So I added the following function in order to make sure that if the div is displayed it will have th form havin the required property.
SO I give this function:
<script type="text/javascript">
function addattribute()
{
if (document.getElementById('montant').style.display == "block")
{
document.getElementsByName('montant_creance').setAttribute('required');
document.getElementsByName('condition2').setAttribute('required');
}
if (document.getElementById('montant').style.display == "none")
{
document.getElementsByName('montant_creance').setAttribute('required','false');
document.getElementsByName('condition2').setAttribute('required','false');
}
}
</script>
But It say to me in the console:
Uncaught TypeError: Object #<NodeList> has no method 'setAttribute'
I really do not know how to find an issue.
Receive all my utmost Respect.
Kind Regards.
SP.

getElementsByName return a collection of elements, so you have to write e.g.
document.getElementsByName('montant_creance')[0].setAttribute('required');
every time you use this method (or similar methods, like getElementsByTagName, getElementsByClassName...) using the right index

the setAttribute takes 2 parameters name and value:
setAttribute('name','value');

Related

JQuery to find LI by text and UL by Class

I am working with a list in SharePoint 2013 that creates an unordered list dynamically on mouseover (the List item ECB for those familiar with SharePoint).
The class name that is given has spaces added after at, 1 additional space for each menu item. I'm not sure if this affects the class property value in jquery so that is why I'm using the begins with notation.
I am needing to hide several menu items and I'm not getting alerts in my debug so I'm thinking my syntax is off.
I'm using this:
if($('ul[class^="ms-core-menu-list"] li[text="View Item"]') ! == null) {
alert('F');
} else {
alert('no F');
}
I do not get alerts so either my syntax is wrong and I need assistance with that or the menu item isn't created when this code executes, in which case I'm wondering how it is possible to get at these menu items using jquery as I'm unable to deploy code in my environment.
I've looked at a number of blogs over the past few days but nothing recommended comes close to working for me.
Thank you
If you're trying to find out if the page contains any li tags that with the text "View Item" that are children of ul tags with the class "ms-core-menu-list" you can use this selector:
$('li:contains("View Item")', $('ul.ms-core-menu-list')).length;
In the context of your example:
if($('li:contains("View Item")', $('ul.ms-core-menu-list')).length) {
alert('F');
} else {
alert('no F');
}
Use this :
if($('ul.ms-core-menu-list li[text="View Item"]').length==0)
...
Note that JQuery always returns a JQuery object which is not null.
The thing to remember about jQuery selectors is that they will always return an object. Even if you don't find anything, you are still given the jQuery API to call things like .hide(), .show(), etc. You won't get an error if you haven't selected anything when calling a jQuery method, you just won't have anything selected for the calls to act upon.
What you can do to infer if any elements are selected is by treating it like the psuedo-array that it is -- you can use .length.
In your case,
if ($('ul.ms-core-menu-list li[text="View Item"]').length > 0) {
alert('F');
} else {
alert('no F');
}

javascript this.value doesn't work?

sorry for asking that stupid:D However what did i do wrong here?
html:
<div onclick="prompt()" value="test">test</div>
javascript:
function prompt() {
var error = this.value;
alert("sdsd");
}
Thanks!
First off, <div>s don't have a value attribute, so .value won't work. Second, you should not use inline JavaScript.
What you should do is:
<div id="test" value="test">test</div>
Then:
$(function(){
$('#test').click(function(){
// You need to get the attribute from the element
var error = $(this).attr('value');
});
});
If you must use inline events, then you need to pass the element to the prompt() function. The problem is that it doesn't know what this is. This is why you should bind the event as shown above. Anyway, you can also do:
<div onclick="prompt(this)" value="test">test</div>
Then:
function prompt(ele){
// You can't use `.value` because `<div>`s
// don't have a value property
var error = ele.getAttribute('value');
}
P.S. May I also suggest using data-* attributes for this instead of invalid attributes?
<div id="test" data-value="test">test</div>
Then:
$(function(){
$('#test').click(function(){
var error = $(this).data('value');
});
});
The value of this depends on how the function that it appears in was called.
When the browser calls the onclick function from the event trigger, this is the input.
When you call prompt(), because you provided no context and you are no in strict mode, this is the window.
You need to explicitly pass the value.
onclick="prompt.call(this)"
Better yet, don't use intrinsic event attributes in the first place. They mix your HTML and logic and have a whole collection of gotchas to go with them.
Then you have a second problem.
Div elements don't have values. Only inputs and other form controls do. You would need to use .getAttribute("value") instead of .value … but that still leaves your HTML invalid (as well as inappropriate - div elements aren't designed to be interacted with, they give no visual indication that they should be clicked on, and they won't receive the focus should the user not be using a mouse or other pointing device anyway).
You should use a control designed to be interacted with.
Finally, prompt is a built in function, so you should avoid overwriting it and pick a different name instead.
function show_value(event) {
var value = this.value;
document.body.appendChild(document.createTextNode(value));
}
document.querySelector("button").addEventListener("click", show_value);
<button type="button" value="test">test</div>
Div does not have value attribute.
If you need to get the value inside div element you can do it by innerHTML property.
function prompt() {
var error = this.innerHTML; // OR this.getAttribute("value");
}

Using Jquery function 's argument to run different result

I am using 2 functions to hide and show all different divs in my html. I'm trying to pass a parameter into the function and use if condition to hide or show different div.
Here is my Jquery Hide function
function HideDivs(content){
if(content==="list"){
$("div#temp_block").hide();
}else if(content==="midbtn"){
$(".search_midbtns").hide();
}else if(content==="result"){
$(".search_result").hide();
}else if(content==="edit"){
$("#edit_data").hide();
}
}
and i am using it inside the document ready function
HideDivs("result");
HideDivs("midbtns");
but i can't hide these divs. Is there a way to do this ? I am having so many div to hide and show. Hope this would be a better way to view the js code.
Check your strings "midbtns" !== "midbtn" also check that your class names match.

jQuery - iterate through all elements with class and change their style

I know this is supposed to be simple, but I'm running into multiple problems. First of all, I don't know how to get all elements of a class and change their display. I found the .each method with this sample code:
$('.classname').each(function(index) {
alert(index);
});
What do I need instead of the alert to change the display property of an element from 'none' to block'?
The second problem is, the class name is gathered from a hidden field. Let's name this variable service. When I try to replace the '.classname' with '.'+service I get an error saying 'Syntax error, unrecognized expression: .'.
So the actual code would be something like:
var service=$('#service').val();
$('.'+service).each(function(index) {
alert(index);
});
I'm sure this can't be complicated but I can't figure it out.
Any alternative solution is of course welcome.
Check out .show:
var service=$('#service').val();
$('.'+service).show(); // roughly equivalent to .css('display', 'block');
However, as the documentation for show points out, the method returns the matched elements display property to it's previous state. To explicitly change the display style property to block, use .css:
$('.' + service).css("display", "block");
try fadeIn() and fadeOut()
var service=$("#service").val();
$("."+service).fadeIn();

How to loop though elements based on part of the dom name

I want to hide all the elements on the page that end in _dropMenu via javascript...so this is what i have
window.onload = function() {
hideNav();
};
function hideNav(){
myArray = element("_dropMenu");// this is what need changing
for (i=0;i<=5;i++)
{
i.style.visibility = 'hidden';
}
}
This is obviously wrong but how do I first get all the elements on the page that end with _dropMenu then loop through them and set them to hidden... I would prefer javascript since I only have prototype on the page but if I need to add jquery I will...
jQuery has a selector for finding elements that have an attribute that ends with a given string:
$('[id$="_dropMenu]')
This will be faster if you can narrow it by an element type (e.g. if all the elements you care about are divs, or some such) but will work as is.
Behind the scenes, jquery is just looping through a given set of elements, and checking whether element["id"].substring(element["id"].length-"_dropMenu".length)==="_dropMenu".
Just pointing out the Prototype is very similar to jQuery in this case:
$$('[id$="_dropMenu"]').invoke('hide');
Kudos Jishnu & JacobM for getting the selector first.

Categories

Resources