Posts

Showing posts with the label Jquery

Bootstrap Toast Does Not Show Up

Answer : You need to put the valid option. i:e show, hide or a callback function . See - https://getbootstrap.com/docs/4.2/components/toasts/. $('.toast').toast('show'); <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script> <div class="toast" role="alert" aria-live="assertive" aria-atomic="true"> <div class="toast-header"> <img height="200px" width="200px" src="https://upload.wikimedia.org/wikipedia/commons/f/f9/Phoenicopterus_ruber_in_S%C3%A3o_Paulo_Zoo.jpg" class="rounded mr-2" alt="..."> <strong class="mr-auto">Boots...

Bootstrap-select Add Item And Select It

Answer : You have a typo. Instead of: $('#myselect').append('<option val="'+newitemnum+'">'+newitemdesc+'</option>'); You need: $('#myselect').append('<option value="'+newitemnum+'">'+newitemdesc+'</option>'); Here is a JSFiddle demo: http://jsfiddle.net/xbr5agqt/ The "Add and select 'Soy Sauce' option" button does the following: $("#myselect").append('<option value="'+newitemnum+'">'+newitemdesc+'</option>'); $("#myselect").val(4); $("#myselect").selectpicker("refresh"); One slightly faster approach (used by the "Add and select 'Relish' option" button) is to append the new <option> element with the selected attribute already applied: $("#myselect").append('<option value="'+newitemnum+'" selected=...

AddID In JQuery?

Answer : ID is an attribute, you can set it with the attr function: $(element).attr('id', 'newID'); I'm not sure what you mean about adding IDs since an element can only have one identifier and this identifier must be unique. do you mean a method? $('div.foo').attr('id', 'foo123'); Just be careful that you don't set multiple elements to the same ID. Like this : var id = $('div.foo').attr('id'); $('div.foo').attr('id', id + ' id_adding'); get actual ID put actuel ID and add the new one

Convert JavaScript Object Into URI-encoded String

Answer : Please look closely at both answers I provide here to determine which fits you best. Answer 1: Likely what you need: Readies a JSON to be used in a URL as a single argument, for later decoding. jsfiddle encodeURIComponent(JSON.stringify({"test1":"val1","test2":"val2"}))+"<div>"); Result: %7B%22test%22%3A%22val1%22%2C%22test2%22%3A%22val2%22%7D For those who just want a function to do it: function jsonToURI(json){ return encodeURIComponent(JSON.stringify(json)); } function uriToJSON(urijson){ return JSON.parse(decodeURIComponent(urijson)); } Answer 2: Uses a JSON as a source of key value pairs for x-www-form-urlencoded output. jsfiddle // This should probably only be used if all JSON elements are strings function xwwwfurlenc(srcjson){ if(typeof srcjson !== "object") if(typeof console !== "undefined"){ console.log("\"srcjson\" is not a JSON object"); ret...

Add CSS Rule Via JQuery For Future Created Elements

Answer : This should work: var style = $('<style>.class { background-color: blue; }</style>'); $('html > head').append(style); When you plan to remove elements from the DOM to re-insert them later, then use .detach() instead of .remove() . Using .detach() will preserve your CSS when re-inserting later. From the documentation: The .detach() method is the same as .remove(), except that .detach() keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted into the DOM at a later time. Here is some JavaScript code I wrote before to let me add, remove and edit CSS: function CSS(sheet) { if (sheet.constructor.name === 'CSSStyleSheet' ) this.sheet = sheet; else if (sheet.constructor.name === 'HTMLStyleElement') this.sheet = sheet.sheet; else throw new TypeError(sheet + ' is not a StyleSheet'); } CSS.prototype = {...

Convert XML To JSON (and Back) Using Javascript

Answer : I think this is the best one: Converting between XML and JSON Be sure to read the accompanying article on the xml.com O'Reilly site, which goes into details of the problems with these conversions, which I think you will find enlightening. The fact that O'Reilly is hosting the article should indicate that Stefan's solution has merit. https://github.com/abdmob/x2js - my own library (updated URL from http://code.google.com/p/x2js/): This library provides XML to JSON (JavaScript Objects) and vice versa javascript conversion functions. The library is very small and doesn't require any other additional libraries. API functions new X2JS() - to create your instance to access all library functionality. Also you could specify optional configuration options here X2JS.xml2json - Convert XML specified as DOM Object to JSON X2JS.json2xml - Convert JSON to XML DOM Object X2JS.xml_str2json - Convert XML specified as string to JSON X2JS.json2xml_str - Convert JSON to XML s...

Call Function With SetInterval In JQuery?

Answer : To write the best code, you "should" use the latter approach, with a function reference: var refreshId = setInterval(function() {}, 5000); or function test() {} var refreshId = setInterval(test, 5000); but your approach of function test() {} var refreshId = setInterval("test()", 5000); is basically valid, too (as long as test() is global). Note that there is no such thing really as "in jQuery". You're still writing the Javascript language; you're just using some pre-made functions that are the jQuery library. First of all: Yes you can mix jQuery with common JS :) Best way to build up an intervall call of a function is to use setTimeout methode: For example, if you have a function called test() and want to repeat it all 5 seconds, you could build it up like this: function test(){ console.log('test called'); setTimeout(test, 5000); } Finally you have to trigger the function once: $(document).re...

Can I Use Javascript To Dynamically Change A Video's Source?

Answer : Sure, You can set the src attribute on the source element: document.querySelector("#myVideoTag > source").src = "http://example.com/new_url.mp4" Or using jQuery instead of standard DOM methods: $("#myVideoTag > source").attr("src", "http://example.com/new_url.mp4"​​​​)​ Then you need to call the load method on the video element: videoElement.load() I have faced this problem several times and based on previous experience and digging I can suggest these options: replace video tag completely yes, just re-insert <video> element with new sources. It's straightforward, but effective approach. Don't forget to re-initialize event listeners. assign video URL to video.src this I saw a lot in answers here, on stackoverflow, and also in sources on github. var video = document.getElementById('#myVideo'); video.src = newSourceURL; It works, but you cannot provide browser opt...

Bypass Popup Blocker On Window.open When JQuery Event.preventDefault() Is Set

Answer : Popup blockers will typically only allow window.open if used during the processing of a user event (like a click). In your case, you're calling window.open later , not during the event, because $.getJSON is asynchronous. You have two options: Do something else, rather than window.open . Make the ajax call synchronous, which is something you should normally avoid like the plague as it locks up the UI of the browser. $.getJSON is equivalent to: $.ajax({ url: url, dataType: 'json', data: data, success: callback }); ...and so you can make your $.getJSON call synchronous by mapping your params to the above and adding async: false : $.ajax({ url: "redirect/" + pageId, async: false, dataType: "json", data: {}, success: function(status) { if (status == null) { alert("Error in verifying the status."); } else if(!status) { $("#agreement...

Call Custom Confirm Dialog In Ajax.Beginform In MVC3

Answer : I came across this to customize AjaxOptions Confirm text with a value that has not been created yet when Ajax.Beginform is rendered . For example: Confirm="Are you sure you want to create Customer Id" + someValue + "?" Finally a found a solution: The approach is regarding a change in submit button behavior with JQuery to pull the value, run my own Confirm dialog and submit the Ajax form if user confirm. The steps: 1- Remove Confirm from AjaxOptions and avoid set button's type="submit", could be type="button" <div> @using (Ajax.BeginForm("Function", "Controller", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "theForm", InsertionMode = InsertionMode.Replace, LoadingElementId = "iconGif", OnBegin = "OnBegin", OnFailure = "OnFailure", OnSuccess =...

Adjust Bootstrap Tooltip Width

Answer : I hope I'm not too late to post this for future programmers looking for answers. There's a question like this one. Go to this link: How do you change the width and height of Twitter Bootstrap's tooltips? One of the answers there is very useful. It was answered by @knobli. I don't know how to link the answer but I hope you can go to that page and vote it up. Anyway, I'll just copy it right here. For CSS: .tooltip-inner { max-width: 100% !important; } For HTML: <a href="#" data-toggle="tooltip" data-placement="right" data-container="body" title="" data-original-title="Insert Title">Insert Title</a> Just add data-container="body" and you're ready to go.

Adding Data Attribute To DOM

Answer : Use the .data() method: $('div').data('info', '222'); Note that this doesn't create an actual data-info attribute. If you need to create the attribute, use .attr() : $('div').attr('data-info', '222'); jQuery's .data() does a couple things but it doesn't add the data to the DOM as an attribute. When using it to grab a data attribute, the first thing it does is create a jQuery data object and sets the object's value to the data attribute. After that, it's essentially decoupled from the data attribute. Example: <div data-foo="bar"></div> If you grabbed the value of the attribute using .data('foo') , it would return "bar" as you would expect. If you then change the attribute using .attr('data-foo', 'blah') and then later use .data('foo') to grab the value, it would return "bar" even though the DOM says data-foo="blah...

Confirm Deletion Using Bootstrap 3 Modal Box

Answer : You need the modal in your HTML. When the delete button is clicked it popup the modal. It's also important to prevent the click of that button from submitting the form. When the confirmation is clicked the form will submit. $('button[name="remove_levels"]').on('click', function(e) { var $form = $(this).closest('form'); e.preventDefault(); $('#confirm').modal({ backdrop: 'static', keyboard: false }) .on('click', '#delete', function(e) { $form.trigger('submit'); }); $("#cancel").on('click',function(e){ e.preventDefault(); $('#confirm').modal.model('hide'); }); }); <link href="http://getbootstrap.com/2.3.2/assets/css/bootstrap.css" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"...

Ajax - JSON Doesnt Get Sent In PATCH Only

Answer : First, check that you use latest version of jQuery library: Older versions directly restrict unknown methods (PATCH is new one). I've tested on jQuery 1.7 - PATCH method working without problems. Second, not all browsers supports PATCH method using XMLHttpRequest: Like, IE 7,8 (9+ works okay) have XMLHttpRequest, but it throws an error on PATCH: new XMLHttpRequest().open('PATCH', '/'); //Illegal argument To fix this, you may force jQuery to use the old proprietary ActiveXObject xhr, like so: $.ajax({ url : 'http://127.0.0.1:8001/api/v1/pulse/7/', data : data, type : 'PATCH', contentType : 'application/json', xhr: function() { return window.XMLHttpRequest == null || new window.XMLHttpRequest().addEventListener == null ? new window.ActiveXObject("Microsoft.XMLHTTP") : $.ajaxSettings.xhr(); } }); A bit late, but this worked for me when I got...

Copy To Clipboard With Break Line

Answer : You have a few problems with the code. First problem in your code is the $(element).text() jquery text() strips your code from html including the <br> tags. So there is no newlines in the clipboard text since all html newlines are stripped away.. so nothing to replace. If you want to keep <br> as newlines you need to use .html() and parse your text more manually. Second problem is that you use <input> tag. <input> tag is only single lines so u cant have any newline in there. you need to use <textarea> for the conversion. The last problem is as above that you also should use \r\n for windows users. I updated your snippet with a working version. function copyToClipboard(element) { var $temp = $("<textarea>"); var brRegex = /<br\s*[\/]?>/gi; $("body").append($temp); $temp.val($(element).html().replace(brRegex, "\r\n")).select(); document.execCommand("copy"); $temp.remove(); } $...

Ajax Add To Cart Button For Product Variation In WooCommerce 3

Answer : To make it work I use a custom ajax add-to-cart for product variations exclusively. 1). I have first changed a bit your button html: <div class="btnss"> <span class="price"> <span class="woocommerce-Price-amount amount">6,999&nbsp; <span class="woocommerce-Price-currencySymbol">kr</span> </span> </span> <div class="quantity buttons_added"> <input type="button" value="-" class="minus"> <label class="screen-reader-text" for="quantity_5b101f605f067">Quantity</label> <input type="number" id="quantity_5b101f605f067" class="input-text qty text" step="1" min="1" max="" name="quantity" value="1" title="Qty" size="4" pattern="[0-9]*" inputm...

Bootstrap Wysihtml5 Set Value Not Working

Answer : You should be able to achieve the same using below $("#<%=txtDescrizioneBreveCategoria.ClientID%>").wysihtml5(); window.describeEditor = window.editor; And then later you should can use describeEditor.setValue(c.DescrizioneBreve, true) or use editorDescrizioneBreve.data("wysihtml5").editor.setValue(c.DescrizioneBreve, true); Where editorDescrizioneBreve is the object returned by $("#<%=txtDescrizioneBreveCategoria.ClientID%>").wysihtml5() PS: Solution based on https://github.com/jhollingworth/bootstrap-wysihtml5/issues/52 For me, this worked: $('.wysihtml5-sandbox').contents().find('body').html(descr) I have only one Wysihtml5 on my page, with multiple, you need to use more precise selector.

Can I Limit The Length Of An Array In JavaScript?

Answer : You're not using splice correctly: arr.splice(4, 1) this will remove 1 item at index 4. see here I think you want to use slice: arr.slice(0,5) this will return elements in position 0 through 4. This assumes all the rest of your code (cookies etc) works correctly The fastest and simplest way is by setting the .length property to the desired length: arr.length = 4; This is also the desired way to reset/empty arrays: arr.length = 0; Caveat: setting this property can also make the array longer than it is: If its length is 2, running arr.length = 4 will add two undefined items to it. Perhaps add a condition: if (arr.length > 4) arr.length = 4; Alternatively: arr.length = Math.min(arr.length, 4); arr.length = Math.min(arr.length, 5)

Add Selected Attribute To Option In Select Menu With JQuery

Answer : As of jQuery 1.6 "To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method." $("#someselect option[value=somevalue]").prop("selected", "selected") Edit: Select Option: $("#someselect option[value=somevalue]").prop("selected", true) Deselect Option: $("#someselect option[value=somevalue]").prop("selected", false) Check out this previous detailled answer on SO: If you really want to maitain HTML output with selected attribute, and not only have jQuery maitaining the right selectedIndex attribute on the select element, you can hack with original settAttr() function: select[0].options[select[0].selectedIndex].setAttribute('selected','selected'); But as soon as you keep using jQuery methods for val() or ':selected', you should'nt get any problem, you could have problem only if you were par...

CSS Set Div 'top' With Jquery From Div 'height'

Answer : You will need to set the css property 'top' on the #footer div, not call .top() on the div itself. $("#footer").css('top', $("#text").height() + "px"); or along those lines Replace .top with .offset({top: somenumber}) http://api.jquery.com/offset/