Select partial ID name in javascript - javascript

I have an asp.net webform where I include the following script (on a separate .js file):
function pageLoad() {
var mpe = $find("mpeEmpresa");
mpe.add_shown(onShown);
$addHandler(document, "keydown", onKeyDown);
}
function onShown() {
var background = $find("mpeEmpresa")._backgroundElement;
background.onclick = function() {
$find("mpeEmpresa").hide();
}
}
Unfortunately, it won't work because asp.net 3.5 changes the elements id's. The only way I could get it to work is to use ctl00_ContentPlaceHolder1_empresaFilha_mpeEmpresa as the ID.
Sure I could use <%= mpeEmpresa.ClientID %> from the asp.net side, it would work but I'll have to pass that as a var to my external .js file and it's not exactly what I'm trying to accomplish.
I have searched on a few ways to select the element by it's ID name partially, but couldn't get any of them to work... Is there a guaranteed way?

I can see the JQuery tag on your question, so you can easily use this:
$('div[id*="mpeEmpresa"]')
As i know the ContentPlaceHolders are rendered as div.
Update:
If you need to select empresaFilha too so you can't use the above selector.
because $('div[id*="mpeEmpresa"]') select both of ctl00_ContentPlaceHolder1_empresaFilha and ctl00_ContentPlaceHolder1_empresaFilha_mpeEmpresa.
so you need to use this:
Select only mpeEmpresa:
$('div[id*="mpeEmpresa"]').css("background-color","blue");
Select only empresaFilha:
$('div[id*="mpeEmpresa"]').parent('div[id*="empresaFilha"]').css("background-color","red");
Or something like this, maybe this code isn't so optimized because i don't see your ASP code or rendered HTML so have to provide a general solution.

You can simply use this
var mpe=$('div[id$="mpeEmpresa"]');
or
var mpe=$find('div[id$="mpeEmpresa"]');

Related

Export HTML DataTable in PDF

I have a simple HTML table with a dropdown filter, i want to export this table in PDF, and when i use the filter that changes the pdf too. If someone can help me that will be good :)
Data table: https://jsfiddle.net/hk8mvyda/
<SCRIPT language="Javascript">
function filterText()
{
var rex = new RegExp($('#Position').val());
if(rex =="/All/"){clearFiltre()}else{
$('.content').hide();
$('.content').filter(function() {
return rex.test($(this).text());
}).show();
}
}
function clearFiltre()
{
$('.Position').val('');
$('.content').show();
}
</script>
PS: Sorry for my english
The filter uses javascript. If you want to be able to render the html to a PDF it will need to be something PHP can access. Since javascript does the change on the clients browser, PHP can not access it unless you use a Http request to get the html.
Use file_get_contents(url) to query the url and allow for a url variable to auto select the content of the dropdown. This way PHP can obtain the rendered HTML after the javascript has done what it needs to do .
http://php.net/manual/en/function.file-get-contents.php
Check this both jquery plugin example it maybehelpful to you
https://w3lessons.info/2015/07/13/export-html-table-to-excel-csv-json-pdf-png-using-jquery/
https://www.phpflow.com/php/export-html-table-data-to-excel-csv-png-and-pdf-using-jquery-plugin/

Update some fields on change and on load

We have the following script which runs on a change to a drop-down - updates the price based on the currency code chosen. This basically gets the value of the drop-down and updates the priceamm and preicecurr fields within the text on the page.
<script>
function run() {
var f = document.getElementById("dropPrice");
priceamm.innerHTML = f.options[f.selectedIndex].value;
var e = document.getElementById("dropPrice");
pricecurr.innerHTML = e.options[e.selectedIndex].text;
}
HTML
<select id="dropPrice" onchange="run()" class="fa-select">
<option value = "a">aaa</option>
<option value = "b">bbb</option>
Question
Now, we would also like to load the drop-down to one of the options (selected) when loading the page (onload). We are able to populate the variables in the text but not the drop-down to show option bbb. In php this is quite easy but we are a bit lost with javascript. We tried something on these lines onload but does not work:
document.getElementById("dropPrice").value = "<?php echo $geo_price ;?>";
With jQuery this is probably easier but once again no luck:
window.onload = function() {
jQuery(document).ready(function($){
document.getElementById('dropPrice').find('option[value=<?php echo $geo_price ;?>]').attr('selected','selected');
});
}
Any help is appreciated. Thanks
The jQuery selector part is incorrect. You are mixing plain JS with jQuery. When you call document.getElementById('dropPrice') a regular DOM element is returned, but then you call find which is a jQuery method to be used on a jQuery element. So, you either need to wrap the first part to return a jQuery element like so:
$(document.getElementById('dropPrice'))
.find('option[value="b"]').attr('selected', true);
Or, select it via jQuery in the first place like:
$('#dropPrice [value="b"]');
However, your first example:
document.getElementById("dropPrice").value = "b";
should work. That makes me wonder if the value that is being echoed by PHP is correct and/or if there are other JS errors being thrown that would cause that code not to run.

How to move onclick code to one place using something like class. Repeated code at various html tags

onclick="triggersTracking($(this).attr('a'),$(this).attr('b'),$(this).attr('c'),Enum.BtnSellerView)"
I have this line at various HTML tags/buttons. I want to move this code to one place for better maintainability. The problem is with third/last attribute i am passing since its Enum, it has different values being passed from different tag elements.
How can i move it to one common place where it would get invoke. For example I could have made a class if i have had just these (this).attr since its common for every tag.
You can do like
Give all the elements a common class name
Then add a data attribute, "data-enum" to each tag with corresponding value.
Then you can write the code like this,
$(".className").click(function () {
var a = $(this).attr('a');
var b = $(this).attr('b');
var c = $(this).attr('c');
var enum = $(this).data('enum');
});
You can use jquery to get this:
$("body").on("click", "someClass", function() {
//code here
});
you don't need to write $(this).attr('a'),$(this).attr('b'),$(this).attr('c')
again and agin on every onclick just paas this object and get them all in function like :
onclick="triggersTracking(this,Enum.BtnSellerView)"
function triggersTracking(obj,enumVal){
// get these values here by obj (no repetitive code needed in every onclick )
$(obj).attr('a')
$(obj).attr('c')
$(obj).attr('b')
}
Do some thing like this
.click()
.on()
.data()
if you use attributes like data-enum , data-e....
so use $(this).data() it will return all attributes in JSON which is starting
from data-
$('.click').click(function(e) {
console.log($(this).data())
$('body').append($(this).attr('a'))
})
// if you have dynamic html tag then go for .on
$('body').on('click','.click',function(){
//callback
console.log($(this).data())
$('body').append($(this).attr('a'))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="click" a="i am a attr of p" b="i am b" data-a="i am data a">i am p</p>
<h2 class="click" a="i am a attr of h2">i am h2</h2>

Convert jQuery to pure JavaScript

I'm having problems trying to convert this piece of code from jQuery into pure JavaScript.
I've wrote everything down in a JSFiddle as example.
The script is
$(".button").click(function () {
$pageID = $(this).attr('name');
var htmlString = $('#' + $pageID).html();
$('#1').html(htmlString);
});
$(".button").click(function () {
$(".button").css('background-position', '0px 0px');
$(this).delay(50).css('background-position', '0px -40px');
});
$(document).ready(function () {
$("[name='page1']").trigger('click');
});
For the first block I've used
function changeNavigation(id){
document.getElementById('1').innerHTML=document.getElementById(id).innerHTML;
}
And in each <div id="button"> added onclick="changeNavigation(id);" replacing id with page1 page2 etc for their respective buttons.
Which seems to work fine. The problem is the second block of code.
I tried using
document.getElementById("button").style.background-position="0px -40px";
Changing the class to an id attribute, just to test it, but it doesn't work.
What could be the problem? Is it that pure JS doesn't support background-position?
Also, as last thing, is it possible to use .innerHTML to write JS code?
I've tried using both JS and jQuery to write Scripts and despite both writing the same exact thing, the written code didn't work with .innerHTML.
Try
style.backgroundPosition
instead of
style.background-position
Thanks to Anthony Grist.
You have used class not ID. So It would be something like
document.getElementsByClassName("button")[0].style.backgroundPosition="0px -40px"
The hyphen is not valid in property names in JavaScript. Therefore, the CSS property background-position is called backgroundPosition in JavaScript.

Wrapping a jquery validate span.error with nested divs

Heyo. This is my first stack overflow post because I am stumped and not finding many people who are trying to accomplish the same thing. I've tried using jquery .before(), .after(), and .wrap() to resolve this. I was initially using css :before and :after pseudo-elements, but as that won't work for legacy browsers, I've decided to use jquery.
I already have several forms on several pages with validation working. The error messages vary in length. We were using a static, one size background image on the default span element, so content was bleeding out on longer error messages. I built a flexible rounded corner series of nested divs to allow the error box to grow or shrink dynamically. The html I want to output is:
<div class="errorWrap">
<div class="errorTop"><span></span></div>
<div class="errorContent">
<span class="error">This is an error</span>
</div>
<div class="errorBottom"><span></span></div>
</div>
Here's an example of a solution I tried, but I'm still pretty new to javascript.
$('.error').before('<div class="errorWrap"><div class="errorTop"><span></span></div><div class="errorContent">');
$('.error').after('</div><div class="errorBottom"><span></span></div></div>');
Correct me if I'm wrong, but I think that I have the right idea with the jquery. But it's just kind of sitting there, not in any function being called. So I imagine that since the code isn't re-executing, it just doesn't show up. Is there an appropriate function to wrap this in? I'm certain I'm just not attacking this from the right direction. Any help is super appreciated.
the plugins "before" and "after" dont take html as string. you cannot start a div in one and close it in an other.
Either you take your current html and generate a new html string which you append where you want to or you use the "wrap" plugin http://api.jquery.com/wrap/
Using pure HTML
$(".error").html("<div class='beforeContent'>" + $(".error").html() + "</div>");
Using wrap (http://api.jquery.com/wrap/)
$(".error").wrap("<div class='beforeAndAfter'></div>");
If you want to show an error div after focus out of an input then you have to create it using html/wrap as Luke said and then you have to append it in ot the dom useing
$('.errorWrap').insertAfter('.focusedElement');
But there are other methods available to insert a new element like append/appendTo e.t.c,
I ended up fixing this problem on my own using jquery to create the div and it's nesting on pageload, the divs are generated with an error class that gives display:none. A custom errorPlacement function nests the error in the correct div. Then I used a custom validator highlight function to remove the class that hides the element. Then I used the unhighlight function to re-add the class to re-hide the div.
$(function() {
//Generate the elements and assign attributes
var errorWrap = document.createElement('div');
$(errorWrap).addClass('errorWrap hideError');
var errorTop = document.createElement('div');
$(errorTop).addClass('errorTop');
var topSpan = document.createElement('span');
var errorContent = document.createElement('div');
$(errorContent).addClass('errorContent');
var errorBottom = document.createElement('div');
$(errorBottom).addClass('errorBottom');
var bottomSpan = document.createElement('span');
//Place the elements directly after each dd element
$("dl > dd").append(errorWrap);
$("div.errorWrap").append(errorTop)
.append(errorContent)
.append(errorBottom);
$("div.errorTop").append(topSpan);
$("div.errorBottom").append(bottomSpan);
//Add custom validator defaults
$.validator.setDefaults({
errorPlacement: function(error, element) {
$(element).nextAll('.errorWrap').children('.errorContent').append(error);
},
highlight: function(element) {
$(element).nextAll('.errorWrap').removeClass('hideError');
},
unhighlight: function(element) {
$(element).nextAll('.errorWrap').addClass('hideError');
}
});
}
Although I'm sure this could have been done more shorthand, I really like this technique because I didn't have to update any of my pages that contained forms to get it to work. All of the nested divs are dynamically created by javascript, so I can include a global file to any page with forms and it will just work. Thanks for all who offered suggestions.

Categories

Resources