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')
Related
I'm working on method that has it's purpose to get elements from a form so that the form can be previewed before submitting. Currently I'm stuck on a problem where I'm trying to get labels from checked checkboxes and separate them. Getting the labels is no problem, but finding a neat way to split them with '( | )' is. I know adding an array possibly would solve my problem, but I was looking for an alternative way to do this in JS/Jquery by simply adding a built in method or similar.
JS and Jquery for what I currently have:
function previewForm() {
const previewPlace = document.getElementById('previewPlace');
let getPlaceChecked = $(':checkbox[name=placeCheckbox]:checked');
if (getPlaceChecked.next('label').text() === "") {
previewPlace.innerHTML = 'No place chosen.'
} else {
previewPlace.innerHTML = getPlaceChecked.next('label').text();
}
}
HTML (actual form):
<div class="custom-checkbox custom-checkbox-padding custom-control">
<input class="custom-control-input" id="norway" name="placeCheckbox" type="checkbox" value="Norway">
<label class="custom-control-label" for="norway">Norway</label>
</div>
<div class="custom-checkbox custom-checkbox-padding custom-control">
<input class="custom-control-input" id="sweden" name="placeCheckbox" type="checkbox" value="Sweden">
<label class="custom-control-label" for="sweden">Sweden</label>
</div>
HTML (preview):
<p class="media-description" id="previewPlace"></p>
So far I've tried simply adding space like below. I've also tried appending, but it doesn't work the way I thought it would.
previewPlace.innerHTML = getPlaceChecked.next('label').text() + " | ";
Edit: typo in if-statement
Edit1: Made a quick fiddle to better demonstrate my problem https://jsfiddle.net/d1nryuqg/
Edit2: Made changes in 'HTML (actual form)' to better fit the jsfiddle..
When you use .text() on a collection (of more than one element), it combines all of the values into a single string - there's no nice way to separate them.
Instead, you can use jquery .map to give you an array of strings for each label, then .join to separate them:
previewPlace.innerHTML = getPlaceChecked.next("label").map((i,e)=>e.innerText).toArray().join(", ")
Updated fiddle: https://jsfiddle.net/6p1h853t/
Unfortunately my front end skills are lacking as my role puts me more on the server side / db technologies as opposed to css / js. In any event, I am trying to implement this:
https://github.com/blueimp/jQuery-File-Upload/wiki/Complete-code-example-using-blueimp-jQuery-file-upload-control-in-Asp.Net.
And more specifically I was able to find an asp.net example here:
http://www.webtrendset.com/2011/06/22/complete-code-example-for-using-blueimp-jquery-file-upload-control-in-asp-net/
Basically allowing you to do mass image uploads.
I've set up the front end with the correct css and js files. I had to modify some of the js files to make use of on() instead of live() as live is deprecated. My form loads and looks like the following:
So far so good, however, as soon as I "Add file" or drag and drop a file chrome developer tools tells me the following:
Uncaught TypeError: Cannot read property '_adjustMaxNumberOfFiles' of undefined
It specifies the file as jquery.fileupload-ui.js and more specifically points me to this:
var that = $(this).data('fileupload');
that._adjustMaxNumberOfFiles(-data.files.length);
I alerted that and of course it seems to be undefined...But I don't know enough jquery to understand why it is undefined. My fileupload div markup was as follows:
<div id="fileupload">
<form action="/Handler.ashx" method="POST" enctype="multipart/form-data">
<div class="fileupload-buttonbar">
<label class="fileinput-button">
<span>Add files...</span>
<input id="file" type="file" name="files[]" multiple>
</label>
<button type="submit" class="start">Start upload</button>
<button type="reset" class="cancel">Cancel upload</button>
<button type="button" class="delete">Delete files</button>
</div>
</form>
<div class="fileupload-content">
<table class="files"></table>
<div class="fileupload-progressbar"></div>
</div>
</div>
So what could be causing this to be undefined? This is what _adjustMaxNumberOfFiles does
_adjustMaxNumberOfFiles: function (operand) {
if (typeof this.options.maxNumberOfFiles === 'number') {
this.options.maxNumberOfFiles += operand;
if (this.options.maxNumberOfFiles < 1) {
this._disableFileInputButton();
} else {
this._enableFileInputButton();
}
}
},
I'm using jquery 2.0.3 and jquery ui 1.10.3
Update
I've gotten it down to the point that the example link which I posted (2nd link above) the only difference is the version of jquery they are using, appears to be 1.8.2 and I am using 2.0.3. The difference and problem is this piece of code:
var that = $(this).data('fileupload');
In the example download this returns some strange object:
a.(anonymous function).(anonymous function) {element: e.fn.e.init[1], options: Object, _sequence: Object, _total: 0, _loaded: 0…}
In my version (using 2.0.3) I am getting undefined for this:
var that = $(this).data('fileupload');
Is there another way I can do this one line of code?
After much playing around in the console window I got it with this:
var that = $("#fileupload").data('blueimpUI-fileupload');
So for anyone that is using anything > jQuery 1.8 please change this line:
var that = $(this).data('fileupload');
to this:
var that = $("#fileupload").data('blueimpUI-fileupload');
How are you initializing the plugin? The issue might be your selector. Target the form itself, vs. the wrapping div.
Based on your html...
Try changing: $('#fileupload').fileupload({ /*options*/ });
To: $('#fileupload form').fileupload({ /*options*/ });
Also, you may have to move your .fileupload-content div inside of the form tag as well.
I can't for the life of me figure out why this isn't working.
I want to search the current page for text using a search box. I googled and found this: http://www.javascripter.net/faq/searchin.htm . I implemented the code into my site, but it doesn't work. the function ( findString() ) works, but only when I hard-code a string (as in i can't use javascript or jquery to get the value of a text input). I made this fiddle: http://jsfiddle.net/alyda/CPJrh/4/ to illustrate the problem.
You can uncomment different lines to see what I've tested.
jQuery has a method :contains() that will make easier what you are looking for.
Take a look here: fiddle
$("button[type='submit']").click(function () {
var string = $('#search').val();
var matched = $('li:contains(' + string + ')');
matched.css('color','red');
console.log(matched);
return false;
});
I found a fix (sort of). It seems that the input needs to be placed well AFTER the content to be searched in the DOM. That means I've done the following:
<section class="content">
<h2>Fire</h2>
<h3>Fire Extinguishers</h3>
<ul>
<li>Model 240</li>
<li>Model C352, C352TS</li>
<li>Model C354, C354TS</li>
</ul>
...
<div id="navbar">
<ul>
...
</ul>
<input id="search" type="text" class="form-control pull-left" placeholder="Search for part number">
<button id="submit" type="submit" class="btn btn-default pull-left" style=" margin-top:6px;">Search</button>
</div>
as you can see, I've moved the input (which is in the navbar div) BELOW all of the text I want to search, and used CSS to programmatically place the navbar at the top of the page. I don't particularly like this setup (as it messes with the flow of content) but since I was looking for the quickest and simplest implementation of a single-page search, it will have to do.
I would still love to know why this happens, when the javascript is at the end of the DOM where it belongs...
In firefox I noticed that the fiddle (v4) as given in the question worked, but not in the way the asker expected it to.
What happens in firefox is that the function does find the value..: you have just entered it in the input-field. Then the browser's find method seems to hang in the 'context' of the input 'control' and doesn't break out of it. Since the browser will continue to search from the last active position, if you select anything after the input-field, the function works as expected. So the trick is not to get 'trapped' in the input-field at the start of your search.
A basic (dirty) example on how to break out of it (not necessarily the proper solution nor pure jquery, but might inspire a useful routine, since you now know the root of the problem in FF):
$( "button[type='submit']" ).click(function(){
var tst=$('#search').val(); //close over value
$('#search').val(''); //clear input
if(tst){ //sanity check
this.nextSibling.onclick=function(){findString( tst );}; //example how to proceed
findString( tst ); //find first value
} else { alert('please enter something to search for'); }
return false;
});
Example fiddle is tested (working) in FF.
PS: given your specific example using <li>, I do feel Sergio's answer would be a more appropriate solution, especially since that would never run line: alert ("Opera browsers not supported, sorry..."), but the proper answer to your window.find question is still an interesting one!
PS2: if you essentially are using (or replicating) the browser's search-function, why not educate the user and instruct them to hit Ctrl+F?
Hope this helps!
I had same problem in an angularjs app and I fix it by changing DOM structure.
my HTML code was something like this:
<body>
<div class="content" >
<input class="searchInput" />
<p>
content ....
</p>
</div>
</body>
and I changed it to something like this:
<body>
<div class="search">
<input class="searchInput" />
</div>
<div class="content">
<p>
content ....
</p>
</div>
</body>
Note: I'm aware that this topic is old.
I have a search box that needs to be within a form so that it can post to another page for a search functionality to work.
I originally had this working fine in Firefox by using an iFrame, but using the search box would simply refresh the when using Internet Explorer.
I found out that it worked fine if I simply created another form underneath the current one, however this obviously leaves it in the wrong place on the page.
I attempted to use the jQuery clone() method that I have succesfully used elsewhere on the site, but this is refusing to work.
I looked around and found another way of using the clone() method and I have it working fine within jsfiddle, but it will not work on my site.
This is the div that I want to populate:
<div id="CustomerSearch">
2
</div>
And this is the div that I want to be cloned:
<form name="frmCustomerList" action="../CustomerList/default.asp" method="post">
<div id="CustomerSearchClone">
1
Customer Search: <br />
<input type="text"id="txtSearch" name="txtSearch" class="Searchbox" />
<input type="submit" value="View" name="txtSearchSubmit" />
</div>
</form>
This is the script that I am using in an external file:
var CustomerSearch = jQuery('#CustomerSearch');
var CustomerSearchClone = jQuery('#CustomerSearchClone');
CustomerSearch.html(CustomerSearchClone.clone(true));
I have it working in JSFiddle here: http://jsfiddle.net/de9kc/92/
Any ideas?
Thanks guys
I'm not a .NET guy but the div you are pasting too is still within a form tag so I'm not certain that this wouldn't cause a hiccup for .NET at submission time (or postback, or whatever).
However, with respect to getting the cloned form elements where you wanted them per the layout you demonstrate in your question;
I modified the pre-result html like so:
//html
<form id="form1" runat="server">
<div id="CustomerSearch">2 Customer Search:</div>
</form>
<form name="frmCustomerList" action="../CustomerList/default.asp" method="post">
<div id="CustomerSearchClone">1 Customer Search:
<br />
<input type="text" id="txtSearch" name="txtSearch" class="Searchbox" />
<input type="submit" value="View" name="txtSearchSubmit" />
</div>
</form>
then i used this jQuery:
// the vars you already created
var CustomerSearch = jQuery('#CustomerSearch');
var CustomerSearchClone = jQuery('#CustomerSearchClone');
// using .clone(true, true) for deepWithDataAndEvents - not sure if you want this?
// will the .clone(true, true) retain input's link to original form id? I'm uncertain
// using .children() because clone's intended destination already has a div container
CustomerSearchClone.children().clone(true, true).appendTo(CustomerSearch);
// hide clone's source after cloning; no sense in having both search boxes visible
CustomerSearchClone.hide();
Note: Using .clone() has the side-effect of producing elements with duplicate id attributes, which are supposed to be unique. (per http://api.jquery.com/clone/)
But you are appending the cloned elements into a different form tag, so maybe a non-issue.
I'm just learning jQuery myself, but I thought I would give the solution a shot ;-$
JSFiddle here: http://jsfiddle.net/de9kc/190/
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);