Show when div got select or option - javascript

I have an application with info page and edit page
the info page shows the info.
in the edit page i have fields with selectbox etc etc
I want to use same code for both. So I tried
if($('#product').has('option'))
{
console.log('hasSelect')
}
else{
console.log('NOSELECTNO')
}
in single page there is no option or select avaible
but in the edit it is.
How can I make sure it will work (and why is this not working)
edit tried this 2:
var attr = $('#product div').attr('select');
if (typeof attr !== typeof undefined && attr !== false) {
console.log("welmetselect")
}
else
{
console.log("zonderselect")
}
EDIT: HTML
<div id= product>
<div>some more divs</div>
<div> in 1 of the div we have <select><option></option></select></div>
</div>
And html infopage
<div id= product>
<div>only information</div>
<div>only text </div>
</div>

I think you need something like this:
if ($("#product option").length )
If you don't have an option, the length will be 0 (and therefore false)

First of all, you could just give them different IDs, or a class like .info and .edit, and simply check $('#product').hasClass('info'). I do not recommend checking for a specific descendant to identify an element anyway, because you want your code to be as flexible as it can be, and if you decide to add a select element to your info page in the future, for example, to filter out specific items to get info on, your code totally breaks.
Second, why your code is not working, is this.
var attr = $('#product div').attr('select');
select is not an attribute, it's a child. Use children('select') (if it's a direct child) or find('select') (if it's not a direct child).
As a sidenote, you can simplify typeof attr !== typeof undefined to typeof attr !== 'undefined' because we already know typeof undefined is returning 'undefined'.

Related

Is there a way to use a field's value in the Model to set a style attribute dynamically?

I have created a CSHTML email template file to send alerts when a specific event is about to end (i.e. sends an alert 10-minutes before end, then at 5-minutes before end, etc.). I want to highlight the type of event (since there can be more than one) by color to differentiate the messages. What I currently have is this:
<strong style="color: {event color}">#alert.event</strong> is scheduled to end: <strong>#endEasternTime
I would like to be able to set the {event color} based on the value in #alert.event, but I'm not sure that I can. I tried to create a script in the file, but I'm not sure how to get its return value into the style tag:
<script>
// Get the root element
var r = document.querySelector(':root');
// Create a function for getting a variable value
function getEventColor(event) {
// Get the styles (properties and values) for the root
var rs = getComputedStyle(r);
// Get the color associated with the event (default is the border color)
return (event === "event1"
? rs.getPropertyValue('--evt1Color')
: (event === "event2"
? rs.getPropertyValue('--evt2Color')
: (event === "event3"
? rs.getPropertyValue('--evt3Color')
: rs.getPropertyValue('--bdrColor')
)
)
);
}
</script>
Note that I have created HTML variables in the file to match up the colors to other styles in the file (such as border-color) -- for space considerations and clarity, I'm not going to show that here.
Is there a way to do this? If not using the inline CSS above, can I update a class or id on the fly using something like the script method above and, if so, what's the best way. I appreciate any help.
You could use if.. else..
#if (#alert.event == value1)
{
<strong class="color1">
}
else if (#alert.event == value2)
{
<strong class="color2">
}
else {
<strong class="colorn">
}
Or simpler way could be naming the classes based on your event and adding color using CSS.
<strong class="event #alert.event">
The tag has 2 classes (event and the value generated)
Lets say #alert.event = "test", then add the CSS to the class as shown below.
.event.test {
color: <color code>
}

Format text as user inputs in a contenteditable div

I'm attempting to make a page that allows users to input text and it will automatically format the input -- as in a screenplay format (similar to Amazon's StoryWriter).
So far I can check for text with ":contains('example text')" and add/remove classes to it. The problem is that all of the following p tags inherit that class.
My solution so far is to use .next() to remove the class I added, but that is limited since there might be need for a line break in the script (in dialogue for instance) and that will remove the dialogue class.
$('.content').on('input', function() {
$("p.input:contains('INT.')").addClass("high").next(".input").removeClass("high");
$("p.input:contains('EXT.')").addClass("high").next(".input").removeClass("high");
});
I can't get || to work in the :contains parameter either, but that's the least of my issues.
I have a JS fiddle
I've worked on this for a while now, and if I could change only the node that contains the text (INT. or EXT. in this example) and leaves the rest alone that would work and I could apply it to the rest of the script.
Any help would be appreciated, I'm new to the stackoverflow so thank you.
See the comments in the code below for an explanation of what's going on.
Fiddle Example
JQuery
var main = function(){
var content = $('.content');
content.on('input', function() {
$("p.input").each(function() {
//Get the html content for the current p input.
var text = $(this).html();
//indexOf will return a positive value if "INT." or "EXT." exists in the html
if (text.indexOf('INT.') !== -1 || text.indexOf('EXT.') !== -1) {
$(this).addClass('high');
}
//You could include additional "if else" blocks to check and apply different conditions
else { //The required text does not exist, so remove the class for the current input
$(this).removeClass('high');
}
});
});
};//main close
$(document).ready(main);

Text not changing in jQuery

I seem to be doing something wrong in the following code: http://jsfiddle.net/yunowork/qKj6b/1/
When you click next, the text within the span .hiddentext should be displayed in the span .showtext on top and correspond to the right Race (Rn). For example when R3 is highlighted the content of that .hiddentext "Race 3Oregon 14:30" should be displayed within the span .showtext.
This is the line where I make a mistake:
$('.showtext').text($('.hiddentext').first('td:first').text());
What am I doing wrong here?
Let's start simple:
Your problem:
$('.showtext').text($('.hiddentext').first('td:first').text());
you are saing, that, grab all .hiddentext, choose the first that has a td ... witch is not what you have in code, you have, td that contains hiddentext... so, the other way around.
What you want to do is simply get the current NEXT td and grab the hiddentext, so, just change to:
$('.showtext').text($nextCol.find('.hiddentext').text());
Now, can you see that the <br/> is not correctly rendered? That's because you are setting the text property, and you should set the html property.
the final code should be something like:
$('.showtext').html($nextCol.find('.hiddentext').html());
live example: http://jsfiddle.net/qKj6b/8/
Your code:
every time you need to have placeholders to provide some data to a context, please, DO NOT USE HTML TAGS to hold such values and hide them... make the use of the data- attribute, witch is a HTML5 complience, and works very well in any browser even if it does not have not HTML5 support, like IE6.
your table definition (td) that currently is:
<td class="visible" id="r2">
<span class="hiddentext">Race 2<br />Santa Fe 12:00</span>
<strong>R2</strong>
</td>
should be something like:
<td class="visible" id="r2" data-text="Race 2<br />Santa Fe 12:00">
R2
</td>
witch is way easier to read, and from your javascript code, you can easily get this as:
var hiddenText = $nextCol.data("text");
Your code (part 2):
This one is quite simple to know
Every time you are repeating yourself, you're doing it wrong
You have the methods for Next and Prev almost exactly as each other, so, you are repeating everything, for this, you should refactor your code and just use one simple method, this way, any future change only happens in one place, and one place only.
$(".next").click(function(e){
e.preventDefault();
var $nextCol = $('.highlighted').next('td');
MoveCursor($nextCol, 'next');
});
$(".previous").click(function(e){
e.preventDefault();
var $prevCol = $('.highlighted').prev('td');
MoveCursor($prevCol, 'prev');
});
function MoveCursor(col, side) {
var maxCol = 8;
if((side === 'next' && col.length != 0) ||
(side == 'prev' && col.length != 0 && col.index() >= maxCol)) {
$('.highlighted').removeClass("highlighted");
col.addClass("highlighted");
// show current title
$('.showtext').html(col.data('text'));
if (col.hasClass("invisible")) {
col.removeClass("invisible");
col.addClass("visible");
var $toRem;
if(side == 'prev')
$toRem = col.next('td').next('td').next('td').next('td').next('td').next('td');
else
$toRem = $nextCol.prev('td').prev('td').prev('td').prev('td').prev('td').prev('td');
$toRem.removeClass("visible");
$toRem.addClass("invisible");
}
}
}
Live Example: http://jsfiddle.net/qKj6b/22/
It should be
$('.showtext').html($('.highlighted .hiddentext').html());
Similar for the prev link...
or even better, thanks to #balexandre:
$('.showtext').html($nextCol.find('.hiddentext').html());
$('.showtext').html($prevCol.find('.hiddentext').html());
Fiddle
Update to match #balexandre hint: Fiddle 2
Do the following:
var $currCol = $('.highlighted'); //to get the current column
$('.race strong').text($currCol.closest('.highlighted').first('td:first').text());
.hiddentext class selects all the spans and the first() will always return you the first td.
Just make sure you select .hiddentext from the currently highlighted column and you are good to go.
$('.showtext').text($('.highlighted .hiddentext').first('td:first').text());
Try this (Same for both)
$('.showtext').html($currCol.find('span.hiddentext').html());
Working Example.

javascript/jquery- how to check, if an element has text attribute or not

Is there some way of determining at run time, if an element returns value for element.text() or not? Using javascript or jquery?
I.E. some way of checking if an element is pure text, or it is some other type of element?
Why I need a solution to the above---
I am trying to parse through some complicated forms with totally different coding styles (in the way, for example, text values for elements of a radio button may be enclosed in label tags, or they may be directly given, or they may be enclosed in span tags, and so on...)
So I need to parse the form with the form id as wrapper,
now if the text value for a radio button is enclosed in span, and current selected element is radio button, then next element will be the span tag (opening) which I want to do nothing with and move on. The one after that will be the text, and this I want to obtain using this.text().
Hence the whole question...
You can use nodeType to check if an element is pure text (in which case its value will be 3)
<div id="wrapper"><input type='radio' />some text here</div>
$('#wrapper').contents().each(function()
{
alert(this.nodeType);
});
It will alert 1 (for input) and 3 (for text). For type=3, you can use text() to get text value
Note- It'll also taken into account white spaces (as text nodes).
var attr = $(this).attr('name');
// For some browsers, `attr` is undefined; for others,
// `attr` is false. Check for both.
if (typeof attr !== 'undefined' && attr !== false) {
// ...
}
Another way to check:
if( typeof( $(this).attr('name') ) != 'undefined' ) { // ... }
you can create you own extension method of jQuery:
$.fn.hasAttr = function(name) {
return this.attr(name) !== undefined;
};
$(document).ready(function() {
if($('.edit').hasAttr('id')) {
alert('true');
} else {
alert('false');
}
});
<div class="edit" id="div_1">Test field</div>
hi you can check the type of element as follow
<form >
<input type="text" id="a" value="abc"/>
</form>
<script>
var type = document.forms[0].elements[0].type;
alert(type);
</script>

Does javascript cache DOM elements?

I'm using mootools to toggle the display (and existence) of two DOM elements in one of my forms. Then, I am using javascript to validate the form to make sure that all of the required fields were filled in. The problem is that the the browser seems to be caching the elements. For example, I have html like this:
<input name="inputbox" id="inputbox" type="text" />
<select name="selection" id="selection">...</select>
And the javascript for validation is something like this:
if (form.inputbox != null && form.inputbox.value == "") {
//don't submit form
{
else if (form.selection != null && form.selection.value == 0) {
//don't submit form
}
Now, this works fine when the page is first loaded and the input element has been removed. However, when I click the button that replaces the input element with the select element, from then on the form.inputbox and form.selection in the javascript code contain the respective element as it was in its last state in the DOM - even if it is no longer in the DOM. So is the javascript caching the DOM and not updating the elements when they are removed from the DOM? What is going on here, and, more importantly, how should I go about fixing it?
Edit: I am using mootools to do the removing and replacing of the elements, the documentation for the respective functions can be found here and here.
Evaluating an element by name (form.elementName) when non-existent returns undefined. Evaluating the property value of an object ($('elementId')) returns null. Undefined and null are treated differently.
Well, I can answer the second part of my question now: how to fix it. If you are using mootools, then use the dollar function (or getElementById might work) instead of using form.selection and form.inputbox:
if ($("inputbox") != null && $("inputbox").value == "") {
//don't submit form
{
else if ($("selection") != null && $("selection").value == 0) {
//don't submit form
}
It works, but I don't have an explanation for why the other didn't...

Categories

Resources