I have a dataTable with local data consisting of 8 headers/rows. However I'm getting Uncaught TypeError: Cannot read property 'cell' of undefined. I did some investigation and if I comment out only one of the columns then I am not getting error anymore. Seems my table can only show 7 rows. Do you know how to fix this?
mercredi 1 juillet 2015
Ajax Calls Returning Zero in IE/Firefox
Have been working on this for 2 days and can't figure out what is causing this to fail in IE (v11) and Firefox. Works fine in Chrome.
Read a lot of questions on here that covered caching issues with multiple Ajax calls, particularly with IE, but I don't believe that's the issue. This code is actually one of two forms on the page. Both are submitted via jQuery, when a "Submit All" button is clicked. I disabled the first form, though, and the second still doesn't function properly.
Here's the JS/Ajax code for the faulty form submission:
$("body").on( "submit", ".update-guest-email", function(event) {
event.preventDefault();
var form = $(this);
if( form.find('input[name="email"]').val() == "" ) {
return;
}
if (!formChecker(form)){
return;
}
var dataString = {
action : 'update_guest_party',
data : form.serializeArray()
}
$.ajax({
cache: false,
type: "post",
url: ajaxurl, // This is the WP AJAX handler.
data: dataString,
beforeSend: function() {
form.find('input').prop('disabled', true);
},
success: function(response){ //so, if data is retrieved, store it in response
if (response.data >= 1){
form.append('<div class="center confirmed"><span class="dashicons dashicons-yes"></span></div>');
form.removeClass();
} else {
form.find('input').prop('disabled', false);
$(".errors").html("That's weird; it didn't go through. You can try again or <a href='mailto:email@gmail.com'>send us an email</a>.")
$('.errors').slideDown(250);
}
} // Close success response.
}); // Close AJAX.
}); // End form-submit.
Again, that functions as expected in Chrome. Firebug shows POST data correctly:
action update_guest_party
data[0][name] email
data[0][value] brundeezy@gmail.com
data[1][name] table
data[1][value] dw_wedding_mgr_guests
data[2][name] id
data[2][value] 149
But then the response is just a '0' (zero). Per Chrome, the response should look like this:
{"success":true,"data":1}
Any help is greatly appreciated! I also have this on a live server, if it would be helpful to see it in production.
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data - tried to parse a php if/else statment
I am building a search which will list a number of users and I am getting this error when I am trying to load more pages to show more users in Chrome dev tool:
Uncaught SyntaxError: Unexpected token <
But I am getting this error in firebug which I think is more conclusive:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
var result = JSON.parse(res);
Here is my ajax function in my index.volt
function(cb){
$.ajax({
url: '/search/search?q=' + mapObject.q + '&sort=<?php echo $sort;?>' + '&page=' + mapObject.page,
data:{},
success: function(res) {
var result = JSON.parse(res);
if (!result.status){
return cb(null, result.list);
}else{
return cb(null, []);
}
},
error: function(xhr, ajaxOptions, thrownError) {
cb(null, []);
}
});
And here is my searchAction() in my Controller:
public function searchAction()
{
$q = $this->request->get("q");
$sort = $this->request->get("sort");
$searchUserModel = new SearchUsers();
$loginUser = $this->component->user->getSessionUser();
$page = $this->request->get("page");
$limit = 1;
if (!$page){
$page = 1;
}
$list = $searchUserModel->findTeachers($q, $loginUser->id, ($loginUser?true:false), $page, $limit, $sort);
$list['status'] = true;
echo json_encode($list);
}
At first I am not sure if the res status is defined so I added $list['status'] = true but it is not helping. Then I tried to remove the if/else statements and it is also not effective.
I need another pair of eyes as I already confirmed all the other variables are valid (ie. $q, $loginUser, $page, $limit, $sort).
Will be greatly appreciated if you can let me know first before downvoting if you think my question is bad or unclear in the comments so I have a change to edit.
Full screen image gallery on click
On http://ift.tt/1ROop3u, I've got a bunch of different pictures.
I want the user to be able to click on an image, then go into a sort of full screen image gallery with arrows going back and forth to switch between images and an X button to go back to the main photography page.
I have separate images on my server that are full resolution.
Would I just make the current images links that go to pages for each of the full screen/resolution images? I feel like there is a much easier way to do this. Any help on the matter would be greatly appreciated!
Thanks for your time!
Trigger events when pageYoffset >= div.offsetTop
I am working on a simple navigation for my site which uses the window.pageYoffset to change the label on the only navigation button which is fixed to the document right, and secondly, click actions on the button scrolls to the top position of the respective container based on the label.
Note:
- Container A is dynamic, the height varies based on the height of the images received.
- Container B has fixed height, I've not decided on what the height is going to be but to just get this functionality going I've am considering 700px.
How do I calculate pageYoffset, such that label change is triggered only when the pageYoffset >= containerB.offset.top? I'm not sure if this condition is met and I am changing a wild goose or is there a better way to tackle this problem.
Current Solution
This is my current solution but the label change triggers when the scrollbar is not even close to the topPosition of ContainerB. I've attached a image which depicts the page.
window.addEventListener( "optimizedScroll", function optimizedScrollFunc( ) {
var self = voApp,
gotoTop = document.getElementById( "cc-gototop-js" ),
winPageYOffset = window.pageYOffset,
windowInnerHeight = window.innerHeight,
documentScrollHeight = document.body.scrollHeight,
topStoriesLoadMore = document.getElementById( "cc-tsLoadMoreWrapper-js" );
dom.glanceUIDiv = document.getElementById( "cc-glanceWrapper-js" ).offsetTop;
console.log((winPageYOffset + windowInnerHeight), documentScrollHeight);
if ( winPageYOffset + windowInnerHeight >= documentScrollHeight ) {
console.log("FIRED");
$( gotoTop )
.removeClass( "cc-thisWeek" )
.addClass( "cc-today" );
$( topStoriesLoadMore )
.removeClass( "cc-tsLoadMoreWrapperVisible" );
}
if ( winPageYOffset < 200 ) {
$( gotoTop )
.removeClass( "cc-today" )
.addClass( "cc-thisWeek" );
}
} );
appUtil.f_throttle( "scroll", "optimizedScroll" );
Page Wireframe
Google Charts - MySQL php
hope all is well!
I need some guidance I have a MySQL Table which looks like this
I would like to have a drop-down list of the companies (facebook, google and youtube) - When I select for example: "google" from the drop-down list, it would display the results for each username who has "google in their row. Then count how many there are total for each user. I would like to have the results show for each day, a full month and a full year totals. It would also be very nice to somehow show each time each company was hit by that user. That's why I added the timestamp.
I would want this to show in some kinda nice graph bar chart. I thought of using Google Charts. Maybe there is something better? Maybe easier to work with?
I'm not here posting this to ask for someone to just code this for me, i'm asking for some help to start me out! Any help is appreciated!
I hope this make sense! haha. This seems very complicated for me to code but I love a challenge but I'm pulling my hair out trying to figure this one out.
Thank you,
Timothy
jQuery: How to add the attribute in $(this)?
Example I have 10 textbox and each has the same attribute with different value, say for example they have an attribute data-same with different value and I have something like this in my code
$('#test').each(function(){ $(this).val(); });
and I want to filter the result using the attribute of each textbox. How would I do it? I was thinking on doing something like this
$('#test').each(function(){ $('[data-same="val1"]',this).val(); });
but I'm not sure about it.
How to add a file jquery on view razor?
I have this view and this works fine
as you see I have added a section (required:false) on _layout and until now there is not problem,
@model final2.Models.ObjetosUnidos.HelperVenta
@{
ViewBag.Title = "Index";
}
@*
<>
*@
@section JavaScript
{
<script type="text/javascript">
$(document).ready(
function () {
var $loading = $('#cargando').hide();
$(document)
.ajaxStart(function () {
$loading.show();
})
.ajaxStop(function () {
$loading.hide();
})
$("#btnselectcliente").click(
function () {
$("#diviniciarventa").hide();
$.when(
$.ajax({
type: "post",
dataType: "html",
url: '@Url.Action("mostrarcuerpo", "venta")',
data: { idcliente: $("#selectcliente").val() }
})
).then(
function (data) {
$("#divcuerpo").html(data);
}, function (error) { alert(error.responseText); }
);
}
);
$(this).on("click", "#btnbuscar", function (e) {
/// Do some stuff ...
var idventa1 = $("#idventa").val();
$.ajax({
type: "post",
dataType: "html",
url: '@Url.Action("buscarproducto", "venta")',
data: { texto: $("#txtbuscar").val(), idventa: idventa1 },
success: function (data) {
$("#divtableproductos").html(data);
},
error: function (error) { alert(error.error); }
});
});
var productoid = 0;
var cantidad = 0.0;
var precio = 0.0;
var iva = 0.0;
var nombre = "";
var codigo = "";
var ventaid = "";
var cantidadelegida = 0.0;
$(this).on(
{
click: function () {
productoid = parseInt(this.cells["productoid"].textContent);
cantidad = parseFloat(this.cells["cantidad"].textContent);
precio = parseFloat(this.cells["precio"].textContent);
iva = parseFloat(this.cells["iva"].textContent);
nombre = (this.cells["nombre"].textContent);
codigo = (this.cells["codigo"].textContent);
ventaid = $("#idventa").val();
$("#txtnombre").val(nombre);
$("#txtcodigo").val(codigo);
}
}, "#tableproductos tbody tr");
var colordefault = "";
$(this).on({
mouseenter: function () {
//stuff to do on mouse enter
colordefault = $(this).css("background-color");
$(this).css("background-color", "#ff0");
},
mouseleave: function () {
$(this).css("background-color", colordefault);
}
}, "#tableproductos tbody tr");
$(this).on(
{
click: function () {
cantidadelegida = $("#txtcantidad").val();
if (cantidadelegida < 0 || cantidadelegida > cantidad) {
alert("Cantidad debe estar entre 0 y " + cantidad);
return;
}
texto = $("#txtbuscar").val();
actualizaprodydetalle(productoid, cantidadelegida, ventaid, texto);
}
}, "#btnagregar");
function actualizaprodydetalle(_productoid, _cantidadelegida, _ventaid, _texto) {
$.when(
$.ajax({
async: false,
type: "post",
dataType: "html",
url: '@Url.Action("muestradetalle", "venta")',
data: { productoid: _productoid, cantidad: _cantidadelegida, ventaid: _ventaid }
}),
$.ajax({
async: false,
type: "post",
dataType: "html",
url: '@Url.Action("buscarproducto", "venta")',
data: { texto: _texto, idventa: ventaid }
})
).then(
function (data1, data2) {
$("#divdetalle").html(data1);
$("#divtableproductos").html(data2);
}
);
}
iddetalle = 0;
$(this).on(
{
mouseover: function () {
iddetalle = parseInt(this.cells["iddetalle"].textContent);
}
}, "#tbldetalle tbody tr");
$(this).on(
{
click: function () {
texto = $("#txtbuscar").val();
try {
$.ajax({
type: "post",
dataType: "html",
url: '@Url.Action("actualizadetalle", "venta")',
data: {
iddetalle: iddetalle,
texto: texto
},
success: function (data) {
$("#divmodal").html(data);
},
error: function (dat) {
alert(dat.responseText);
alert(dat.statusText);
}
});
}
catch (ex) {
alert(ex.message);
}
}
}, "#btnmodificar");
$(this).on(
{
click: function () {
var productoid5 = $("#adproductoid").val();
var ventaid5 = $("#idventa").val();
var texto5 = $("#adtexto").val();
if (parseFloat($("#txtnuevacantidad").val()) < 0 || parseFloat($("#txtnuevacantidad").val()) > (parseFloat($("#addisponible").val()) + parseFloat($("#adcantidadactual").val()))) {
alert("Cantidad debe estar entre 0 y " + (parseFloat($("#addisponible").val()) + parseFloat($("#adcantidadactual").val())));
return;
}
var cantidad5 = parseFloat($("#txtnuevacantidad").val()) - parseFloat($("#adcantidadactual").val());
actualizaprodydetalle(productoid5, cantidad5, ventaid5, texto5);
$('#divmodal').html("");
}
}, "#btnnuevacantidad");
$(this).on(
{
click: function () {
var ventaid5 = $("#idventa").val();
try {
$.ajax({
type: "post",
dataType: "html",
url: '@Url.Action("finalizarventa", "venta")',
data: {
ventaid: ventaid5
},
success: function (data) {
$("#divmodal").html(data);
},
error: function (dat) {
alert(dat.responseText);
alert(dat.statusText);
}
});
}
catch (ex) {
alert(ex.message);
}
}
}, "#btnfinalizarvta");
cambiofinal = 0;
$(this).on(
{
keypress: function (e) {
try {
if (e.which == 13) {//Enter key pressed
total = parseFloat($(this).val());
total = total.toFixed(2);
cobrar = parseFloat($("#fvprecio").val());
cobrar = cobrar.toFixed(2);
cambio = (total - cobrar);
cambio = cambio.toFixed(2);
cambiofinal = cambio;
$("#txtcambio").val(cambio);
}
}
catch (ex) {
alert("Solo números flotantos por favór " + ex.message);
return false;
}
}
}, "#txtentrega");
$(this).on(
{
click: function (e) {
$('#divmodal').html("");
}
}, "#fvcerrar");
$(this).on(
{
click: function (e) {
if (cambiofinal < 0) {
alert("Dinero Insuficiente");
return;
}
$('#divmodal').html("");
var ventaid5 = $("#idventa").val();
//ventafinalizada
$.ajax(
{
type: "post",
dataType: "text",
url: '@Url.Action("ventafinalizada", "venta")',
data: { ventaid: ventaid5 },
async: false,
success: function (response) {
alert(response);
window.close();
},
error: function (data) { alert("Ocurrio un errorxx"); }
}
);
}
}, "#fvfinalizarventa");
//$("#buscar").keypress(function (e) {
// if (e.which == 13) {//Enter key pressed
// //$("#btnaceptar").click();//Trigger search button click event
// alert("buscar enter")
// buscar();
// }
//});
});
</script>
}
<div id="cargando">
<img src="~/Images/cargandoajax.gif" />
</div> ...
I know to add the Javascript code in a file is a good practic, then I copy
$(document).ready(
function () {...}
in a file but it does not work
@section JavaScript
{
<script type="text/javascript" src="~/Scripts/scriptventa.js"></script>
}
what am i doing wrong?
I tried doing it too
<script type="text/javascript" src="~/Scripts/scriptventa.js"></script> (not using @section) but it does not work
ajax response needed to be assigned to a div
I am implementing an image gallery using an Ajax call.
The call passes a value and gets an HTML code as a response. I checked this response and it is correct.
And if I put this code into a static DIV, the gallery works with no problems.
But if I inject the code with AJAX, when I click on an image, it opens in the window as a normal image: the gallery pop-up is not working.
What could be the cause of this problem?
The code is as follows
$.ajax({
type: 'GET',
url: 'www.test.com',
data: {
type: product,
use: 'gallery'
},
dataType: 'html',
success: function(data) {
$("#dv_gallery").append(data);
}
});
the following is the HTML code in the page
<div class="portfolio-adaptive adaptive-three" id="dv_gallery"></div>
How can i make my sub-menu slide down and up when click on main item?
$(document).ready(function () {
$('.slideout-menu-toggle').on('click', function(event){
event.preventDefault();
// create menu variables
var slideoutMenu = $('.slideout-menu');
var slideoutMenuWidth = $('.slideout-menu').width();
// toggle open class
slideoutMenu.toggleClass("open");
// slide menu
if (slideoutMenu.hasClass("open")) {
slideoutMenu.animate({
left: "0px"
});
} else {
slideoutMenu.animate({
left: -slideoutMenuWidth
}, 250);
}
});
});
$('.mobile-sub-menu').click(
function() {
$(this).find('li').slideDown();
},
function() {
$(this).find('li').slideUp();
});
.slideout-menu {
position: absolute;
top: 100px;
left: -9999px;
width: 100%;
height: 100%;
background: rgb(248, 248, 248);
z-index: 1;
}
.slideout-menu .slideout-menu-toggle {
position: absolute;
top: 12px;
right: 10px;
display: inline-block;
padding: 6px 9px 5px;
font-family: Arial, sans-serif;
font-weight: bold;
line-height: 1;
background: #222;
color: #999;
text-decoration: none;
vertical-align: top;
}
.slideout-menu .slideout-menu-toggle:hover {
color: #fff;
}
.slideout-menu ul {
list-style: none;
font-weight: 300;
border-top: 1px solid #dddddd;
border-bottom: 1px solid #dddddd;
}
.slideout-menu ul li {
/*border-top: 1px solid #dddddd;*/
border-bottom: 1px solid #dddddd;
}
.slideout-menu ul li a {
position: relative;
display: block;
padding: 10px;
color: #999;
text-decoration: none;
}
.slideout-menu ul li a:hover {
background: #aaaaaa;
color: #fff;
}
.slideout-menu ul li a i {
position: absolute;
top: 15px;
right: 10px;
opacity: .5;
}
<script src="http://ift.tt/1qRgvOJ"></script>
<button type="button" class="slideout-menu-toggle">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<body>
<div class="slideout-menu">
<ul>
<li><a href="#">MANUALS</a>
<ul class="mobile-sub-menu">
<li><a href="#">1</a></li>
<li><a href="#">1</a></li>
<li><a href="#">1</a></li>
</ul>
</li>
<li><a href="#">NEWS</a></li>
<li><a href="#">SPARE PART</a></li>
<li><a href="#">Photo Gallery</a></li>
<li><a href="#">WHERE TO BUY</a></li>
<li><a href="#">SUPPORT</a></li>
<li><a href="#">EDIT BOOK</a></li>
</ul>
</div>
I add some sub-item under MANUALS main item. What can I do to make it invisible and slide down or up when I click on its parent main item?
I try to write some jQuery code but not working. Is something wrong on my jQuery code?
jQuery Overlay Image on HTML5 Video
I am trying to build a small utility where someone can start watching an HTML5 video (not YouTube - this will stream from the same server the site is hosted on), click in a specific area of the video, have it pause and put a small circle on the video where they clicked. Once that occurs, a small window will pop up so the user can comment indicating why they clicked there (something wrong in the video, etc.).
The basic HTML structure is this:
<div id="videoContainer" style="margin-left: auto; margin-right: auto; height: 550px; width: 950px; background-color: #fff">
<video id="pcVideo" src="fvb0375.mov" style="margin-left: auto; margin-right: auto; height: 550px; width: 950px; display:inline;" preload="auto" controls></video>
</div>
The custom styling can be ignored - that was just to center the video on the screen with a generic height/width that won't be used later. The JS on the page (to handle when the video is clicked) is this:
$("#pcVideo").click(function(e) {
//height and width of the container
var height = $("#pcVideo").height();
var width = $("#pcVideo").width();
//get click position inside container
var relativeX = e.pageX - this.offsetLeft;
var relativeY = e.pageY - this.offsetTop;
//overlay
var overlay = $("<div height='75' width='75' class='overlay'/>");
overlay.offset({
top: relativeY,
left: relativeX
});
var circle = $("<img/>");
circle.attr('src', 'circle.png');
overlay.append(circle);
$("#videoContainer").append(overlay);
video.pause();
});
As it stands, the video pauses fine, but the image shows up below the video. If I hide the video, the image pops in right where it is supposed to, so what I've realized is it is applying correctly, but for some reason the video is considered a block-level element, so anything in its realm gets bumped to the "next line" as it were, thus throwing positioning off, like so:
Video shown, circle is below container:
Video hidden, circle shows in appropriate spot:
I've tried z-index with CSS, tried absolute/relative positioning and nothing seems to work to get this thing over top of the video.
Any ideas?
Cannot update textfield based on dropdown list Yii
I have 3 dependent dropdowns, and a textfield being dependent to the last dropdown. If one of the value in the last dropdown, I want the textfield value dynamically changes based on the selected value (it's from the same Database table).
This is the view of the third dropdown:
<div class="row" id="id_subkeg">
<?php echo $form->labelEx($model, 'id_subkeg'); ?>
<?php
echo $form->dropDownList($model, 'id_subkeg', array(), array(
'style' => 'width: 100%',
'ajax' => array(
'type' => 'POST',
'url' => CController::createUrl('dynamicSatuan'),
'update' => '#' . CHtml::activeId($model, 'satuan'),
//'update'=>'#seksi',
'data' => array('id_subkeg' => 'js:this.value'),
)
)
);
?>
<?php echo $form->error($model, 'id_subkeg'); ?>
</div>
This is the textfield view:
<div class="row" id="satuan">
<?php echo $form->labelEx($model, 'satuan'); ?>
<p class="hint" style="font-size: 80%">Contoh: Dokumen.</p>
<?php echo $form->textField($model, 'satuan', array('style' => 'width: 98%;', 'readonly' => FALSE)); ?>
<?php echo $form->error($model, 'satuan'); ?>
</div>
And this is the action in the controller:
public function actionDynamicSatuan() {
//$data = Subkegiatan::model()->findByPk($_POST['id_subkeg']);
$data = Subkegiatan::model()->findByPk('id_subkeg=:id_subkeg', array(':id_subkeg' => (int) $_POST['id_subkeg']));
echo $data->satuan;
}
But it's not been working for days. I don't know which part I've missed. My guess is that the dropdown is a dependent dropdown to the one above it. So I must have missed at some part.
Any help is highly appreciated.
Side Navigation Bar not showing on click of Navigation drawer Bootstrap
I am trying to get a navigation drawer working which is similar to http://ift.tt/1LEGKQY using bootstrap. I have a main navigation bar and I have been able to get a navigation drawer for mobile screens. I have created a sidebar which is hidden by default. On clicking the drawer I want my side navigation bar to appear and the contents of main navigation bar to be not present. However currently when I click the drawer, my side navigation is not shown and all the options of my main navigation bar are still present.
My HTML page source:
<body>
<div class="navbar navbar-inverse navbar-fixed-top" id="primary-nav">
<div class="container"> <a href="#" class="navbar-brand hidden-xs">MyName</a>
<button id="menu-toggle" class="navbar-toggle pull-left" data-toggle="collapse" data-target=".navHeaderCollapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<div class="collapse navbar-collapse navHeaderCollapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#">ABOUT ME<span class="sr-only">(current)</span></a>
</li>
<li><a href="#">RESUME</a>
</li>
<li><a href="#">PROJECTS</a>
</li>
<li><a href="#">BLOG</a>
</li>
<li><a href="#">CONTACT</a>
</li>
</ul>
</div>
</div>
</div>
<div class="container" id="mobile_sideNav">
<div class="row profile">
<div class="col-md-3">
<div class="profile-sidebar">
<!-- SIDEBAR USERPIC -->
<div class="profile-userpic">
<img src="http://ift.tt/1CLubMy" class="img-responsive" alt="">
</div>
<!-- END SIDEBAR USERPIC -->
<!-- SIDEBAR USER TITLE -->
<div class="profile-usertitle">
<div class="profile-usertitle-name">
Marcus Doe
</div>
<div class="profile-usertitle-job">
Developer
</div>
</div>
<!-- END SIDEBAR USER TITLE -->
<!-- SIDEBAR BUTTONS -->
<div class="profile-userbuttons">
<button type="button" class="btn btn-success btn-sm">Follow</button>
<button type="button" class="btn btn-danger btn-sm">Message</button>
</div>
<!-- END SIDEBAR BUTTONS -->
<!-- SIDEBAR MENU -->
<div class="profile-usermenu">
<ul class="nav">
<li class="active">
<a href="#">
<i class="glyphicon glyphicon-home"></i>
Overview </a>
</li>
<li>
<a href="#">
<i class="glyphicon glyphicon-user"></i>
Account Settings </a>
</li>
<li>
<a href="#" target="_blank">
<i class="glyphicon glyphicon-ok"></i>
Tasks </a>
</li>
<li>
<a href="#">
<i class="glyphicon glyphicon-flag"></i>
Help </a>
</li>
</ul>
</div>
<!-- END MENU -->
</div>
</div>
<div class="col-md-9">
<div class="profile-content">
Some user related content goes here...
</div>
</div>
</div>
</div>
</body>
My Javascript Source:
function detectmob() {
if( navigator.userAgent.match(/Android/i)
|| navigator.userAgent.match(/webOS/i)
|| navigator.userAgent.match(/iPhone/i)
|| navigator.userAgent.match(/iPad/i)
|| navigator.userAgent.match(/iPod/i)
|| navigator.userAgent.match(/BlackBerry/i)
|| navigator.userAgent.match(/Windows Phone/i)
){
return true;
}
else {
return false;
}
}
$(document).ready(function() {
$("#mobile_sideNav").hide();
if(detectmob()) {
$("#primary-nav").hide();
}
});
$("#menu-toggle").click( function() {
$("#mobile_sideNav").show();
});
My css:
body {
padding-top: 70px;
}
html, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
.brand-bg, .sweet-alert button {
background-color: #00bcd4 !important;
}
.projects-wrap {
padding: 110px 0;
}
.root-sec {
position: relative;
}
.main-section {
overflow: hidden;
overflow-x: hidden;
overflow-y: hidden;
}
/* Profile container */
.profile {
margin: 20px 0;
}
/* Profile sidebar */
.profile-sidebar {
padding: 20px 0 10px 0;
background: #fff;
}
.profile-userpic img {
float: none;
margin: 0 auto;
width: 50%;
height: 50%;
-webkit-border-radius: 50% !important;
-moz-border-radius: 50% !important;
border-radius: 50% !important;
}
.profile-usertitle {
text-align: center;
margin-top: 20px;
}
.profile-usertitle-name {
color: #5a7391;
font-size: 16px;
font-weight: 600;
margin-bottom: 7px;
}
.profile-usertitle-job {
text-transform: uppercase;
color: #5b9bd1;
font-size: 12px;
font-weight: 600;
margin-bottom: 15px;
}
.profile-userbuttons {
text-align: center;
margin-top: 10px;
}
.profile-userbuttons .btn {
text-transform: uppercase;
font-size: 11px;
font-weight: 600;
padding: 6px 15px;
margin-right: 5px;
}
.profile-userbuttons .btn:last-child {
margin-right: 0px;
}
.profile-usermenu {
margin-top: 30px;
}
.profile-usermenu ul li {
border-bottom: 1px solid #f0f4f7;
}
.profile-usermenu ul li:last-child {
border-bottom: none;
}
.profile-usermenu ul li a {
color: #93a3b5;
font-size: 14px;
font-weight: 400;
}
.profile-usermenu ul li a i {
margin-right: 8px;
font-size: 14px;
}
.profile-usermenu ul li a:hover {
background-color: #fafcfd;
color: #5b9bd1;
}
.profile-usermenu ul li.active {
border-bottom: none;
}
.profile-usermenu ul li.active a {
color: #5b9bd1;
background-color: #f6f9fb;
border-left: 2px solid #5b9bd1;
margin-left: -2px;
}
/* Profile Content */
.profile-content {
padding: 20px;
background: #fff;
min-height: 460px;
}
jQuery using arrow key scrolling during presentation
I'm creating a presentation using HTML for a project I'm working on. The presentation will be full-page slides and I want to implement a script with jQuery so that when the arrow keys are pressed, it scrolls smoothly between slides. Left being previous slide and right being next slide obviously.
I wrote a script but it only works the first time. I'm very new to jQuery and I can't seem to fix it.
The page the presentation will be on is: http://ift.tt/1ekJPbP
<script type="text/javascript">
$(document).keydown(function(e){
if (e.keyCode == 37) {
$('.slide').previous().ScrollTo({
duration: 2000,
easing: 'linear'
});
}
if (e.keyCode == 39) {
$('.slide').next().ScrollTo({
duration: 2000,
easing: 'linear'
});
}
});
</script>
How to access the root element when parsing HTML with jQuery?
How do I access the root element when parsing HTML with jQuery?
More specifically, why does this equals to 0:
$('<div class="messages"><p>Just a test.</p></div><div class="messages">Another test</div>')
.find('div.messages').length == 0
Where this equals to 1 like it should:
$('<div><div class="messages"><p>Just a test.</p></div></div>')
.find('div.messages').length == 1
Okay, I can wrap everything into something every time, but really do I have to?
jquery validate change error messages on invalidHandler
I saw the documentation on jquery validate plugin for invalidHandler on the website. I was hoping to be able to do something like the following?
$(".selector").validate({
invalidHandler: function(event, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
for (var i = 0, len = errors.length; i < len; i++) {
errors[i].text = //replace special characters in message (if any) and replace with something else)
}
}
//update list of changed error messages back to validator, so new error messages show
}
});
I'm trying to do it this way because I'm trying to do it globally. Basically I'm trying to convert a simpler markup into a hyperlink, and was hoping to be able to do this globally.
Is that possible?
return false not preventing form from submitting
I am trying to validate a field using $.get request. I can see the error message("Plan already present") but the form is getting submitted. I want to prevent form from submitting. Here is my code:
$("#add_plan_subscriptions").submit(function(event) {
var flag = true;
var subdomain_val = $('[name="plan[subdomain_type_id]"]').val();
var plan_val = $('[name="plan[plan_type_id]"]').val();
var plan_name = $('[name="plan[plan_name]"]').val();
var subdomain_type_id = subdomain_val;
var plan_name = $('[name="plan[plan_name]"]').val();
$.get("/plans/check_duplicate_plan",{subdomain_type_id: subdomain_type_id, plan_name: plan_name}, function (response) {
if (response){
event.preventDefault() ;
var element = $('[name="plan[plan_name]"]');
var message = "Plan already present";
addError(element,message)
return false;
}
else{
var element = $('[name="plan[plan_name]"]');
removeError(element)
}
})
if(subdomain_val == ""){
var element = $('[name="plan[subdomain_type_id]"]')
var message = "Please select user type"
addError(element,message)
flag = false;
}
if(subdomain_val != ""){
var element = $('[name="plan[subdomain_type_id]"]')
removeError(element)
}
if(plan_val == ""){
var element = $('[name="plan[plan_type_id]"]')
var message = "Please select plan type"
addError(element,message)
flag = false;
}
if(plan_val != ""){
var element = $('[name="plan[plan_type_id]"]')
removeError(element)
}
if (!flag){
event.preventDefault();
return false;
}
return true;
});
Make an ajax call after form checking
I have a form like this:
<form id="update_form_password">
<label for="text-input">Nouveau mot de passe</label>
<input type="password" id="customer_new_password" name="customer_new_password" class="form-control">
<label for="text-input">Répétez le mot de passe</label>
<input type="paswword" id="customer_repeat_password" name="customer_repeat_password" class="form-control">
<button type="submit" class="btn btn-primary"> Enregistrer</button>
</form>
I'm using the jQuery validation plugin to check is my forms are correctly filled.
My problem is to submit the form after the check.
So I have actually:
<script>
$('#update_form_password').validate({
rules: {
customer_new_password: "required",
customer_repeat_password: {
equalTo: "#customer_new_password"
}
}
});
</script>
But how to allow the form submitting and then continue my ajax calls ?
Thanks for your help.
Creating a editor
I'm trying to understand object inheritance in JS with an exercise, create a online editor, like this one that i'm writing on.
But.. i'm a little confuse here, i want use data-* to manipulate my editor:
<div class="editor__wrapper">
<div data-editor="toolbar">
</div>
<textarea data-editor="textarea"></textarea>
</div>
So, i was trying initialize like this:
$(window).on('load', function() {
$('[data-editor]').each(function() {
var element = $(this);
var editor = new Editor(element);
});
});
and the editor:
var Editor = function(element) {
this.element = element;
};
But this is not what i exactly want here..
I want initialize with data-* but create a toolbar if is a toolbar and create an editor if is an editor, but make the two inherit from the a father with commum properties.
I'm little lost here, what you guys think about this? There is a better way???
Thanks.
How do I get a value in jQuery to PERMANENTLY be added to the html file?
Simply, there is a function on my website which allows users to enter text and have it display on a page.
HOWEVER, that text does not stay permanently and disappears when the page is reloaded.
How do I get jQuery to add the text inserted in the textarea to stay on that page once submitted?
This is what my jQuery looks like.
//When the 'button' is clicked, it prints whatever is in the textarea in separate divs
//this is it:
$(document).ready(function() {
$('#button').click(function() {
var toAdd = $('textarea[name=input]').val();
$('.list').append('<div class="posts">' + toAdd + '</div>');
});
});
Please ask me if you don't understand me and thank you in advance for any help :)
visualsearch (faceted query search) using Sencha ExtJS 5
I've been trying to implemented a faceted search autocomplete using Sencha ExtJS 5. Something similar to the "visualsearch" plugin developed using JQuery.
This is what I'd like to do:
So far, this is what I have:
Ext.define('App.custom.SearcherWidget', {
extend: 'Ext.form.field.ComboBox',
alias: 'widget.searcher',
emptyText: 'Select Entity',
isKeySelected: false,
currSelectedKey: null,
facetedQuery: null,
initComponent: function() {
var me = this;
me.store = me.retrieveKeys();//TODO: To be changed
me.queryMode = 'local';
me.displayField = 'description';
me.valueField = 'code';
me.typeAhead = true;
me.minChars = 1;
me.enableKeyEvents = true;
me.triggerAction = 'query';
me.hideTrigger = true;
me.on({
change: me.fixChange,
beforeselect: me.fixBeforeSelect,
beforequery: me.fixBeforeQuery,
keypress: me.checkKeyPressed,
scope: me
});
me.callParent(arguments);
},
checkKeyPressed: function(combo, e, eOpts) {
var me = this,
selectedValue = combo.getValue(),
comboStore = combo.store;
if (selectedValue && selectedValue.length > 0) {
//Not the first time, check if is key or value
if (this.isKeySelected) {
//Is a key
comboStore.loadData(me.retrieveKeys());
} else {
//Is a value and a key is current selected
comboStore.loadData(me.retrieveValuesBasedOnKeys(me.currSelectedKey));
}
comboStore.load();
} else {
//It is empty, so we should check key
comboStore.loadData(me.retrieveKeys());
comboStore.load();
}
},
fixChange: function(combo, newVal, oldVal, eOpts) {
var selectedValue = combo.getValue();
if (!(selectedValue && selectedValue.length > 0)) {
combo.collapse();
} else {
}
},
fixBeforeSelect: function(combo, record, index, eOpts) {
var me = this,
selectedValue = combo.getValue(),
terms = selectedValue.split( /,\s*/ );
if (record && record.get('type') === 'key') {
isKeySelected = true;
me.currSelectedKey = record.get('description');
terms.pop();
terms.push(me.currSelectedKey);
terms.push('');
combo.setValue(terms.join( ': ' ));
combo.collapse();
} else {
// terms.pop();
// terms.push(record.get('description'));
// terms.push('');
// combo.setValue(terms.join( ', ' ));
// combo.collapse();
}
return false;
},
fixBeforeQuery: function(queryPlan, eOpts) {
var terms = queryPlan.query.split( /,\s*/ );
queryPlan.query = terms[terms.length - 1];
return (queryPlan.query && queryPlan.query.length > 0);
},
retrieveKeys: function() {
return Ext.create('Ext.data.ArrayStore', {
fields: [{name: 'code'},
{name: 'description'},
{name: 'type'}],
data: [
[1, 'domain', 'key'],
[2, 'instance', 'key'],
[3, 'attribute', 'key'],
[4, 'relation', 'key']
]
});
},
retrieveValuesBasedOnKeys: function(key) {
var me = this,
rawData = me.retrieveMockValues(),
dataBasedOnKey = [];
for (var i = 0; i < rawData.length; i++) {
var currElement = rawData[i];
if (currElement.type === key) {
dataBasedOnKey.push(currElement);
}
}
return Ext.create('Ext.data.ArrayStore', {
fields: [{name: 'code'},
{name: 'description'},
{name: 'type'}],
data: dataBasedOnKey
});
},
retrieveMockValues: function() {
return [{'code': 1, 'description': 'verizon', 'type': 'domain'},
{'code': 2, 'description': 'terremark', 'type': 'domain'},
{'code': 3, 'description': 'sencha', 'type': 'domain'},
{'code': 4, 'description': 'microsoft', 'type': 'domain'},
{'code': 5, 'description': 'oracle', 'type': 'domain'},
{'code': 6, 'description': 'dev1', 'type': 'instance'},
{'code': 7, 'description': 'dev2', 'type': 'instance'},
{'code': 8, 'description': 'dev3', 'type': 'instance'},
{'code': 9, 'description': 'dev4', 'type': 'instance'},
{'code': 10, 'description': 'dev5', 'type': 'instance'},
{'code': 11, 'description': 'dev6', 'type': 'instance'},
{'code': 12, 'description': 'dev7', 'type': 'instance'},
{'code': 13, 'description': 'dev8', 'type': 'instance'},
{'code': 14, 'description': 'red', 'type': 'attribute'},
{'code': 15, 'description': 'white', 'type': 'attribute'},
{'code': 16, 'description': 'black', 'type': 'attribute'},
{'code': 17, 'description': 'blue', 'type': 'attribute'},
{'code': 18, 'description': 'one-to-many', 'type': 'relation'},
{'code': 19, 'description': 'many-to-many', 'type': 'relation'},
{'code': 20, 'description': 'one-to-one', 'type': 'relation'}
];
},
retrieveEntities: function() {
return Ext.create('Ext.data.ArrayStore', {
fields: [
{name: 'code'},
{name: 'type'},
{name: 'description'}
],
data : [
[1,'Domain','AT&T'],
[2,'Domain','Altria Group Inc'],
[3,'Domain','American Express Company'],
[4,'Domain','Bellcorp'],
[5,'Domain','Claro'],
[6,'Domain','Dell'],
[7,'Domain','E&E'],
[8,'Domain','Farenheit'],
[9,'Domain','Garman'],
[10,'Domain','Hell'],
[11,'Domain','Intel'],
[12,'Domain','Jasper'],
[13,'Domain','Halmington'],
[14,'Domain','LLL Corp'],
[15,'Domain','Verizon'],
[5,'Instance','American Express Company']
]
});
}
});
I tried to adapt the "visualsearch" of JQuery to the ExtJS code... but no success at all... I wonder if somebody could give me a clue or a hand on this.
Any help is appreciated. Thanks in advance.
using refresh token to get access token office 365 rest api
While using the refresh token to get an access token through office 365 REST api I made the following Jquery ajax request.
jQuery.ajax({
url: "http://ift.tt/1Jwc0SJ",
type: "post",
headers:{
"Content-Type":"application/x-www-form-urlencoded"
},
data: {
grant_type: "refresh_token",
refresh_token: access_data['refresh_token'],
client_id: consumer_key,
client_secret: consumer_secret,
resource: "http://ift.tt/1pxDOan"
},
success: function(response){
console.log(response)
}
})
I get the following error
XMLHttpRequest cannot load
http://ift.tt/1Jwc0SJ.
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost' is therefore not allowed access.
The response had HTTP status code 404.
But I was able to make the same POST request in python through requests library using same refresh_token and client credentials and am unable to figure out why the same POST request does not work through jQuery. Any help on this issue is appreciated.
Thanks
Dynamic div displaying incorrectly
I have a dynamic legend being added into a leaflet map.
My issue is where the div.innerHTML +='</div>' gets called before the if statements and for statement have finished.
I've been looking into Callbacks but I'm just really stuck after hours of looking at this, and seem to be going in circles
/*Legend Control */
function maplegendControl() {
dynamicmapLegend = L.control({
position: 'topright'
});
dynamicmapLegend.onAdd = function(map) {
var div = L.DomUtil.create('div', 'legend'),
legendcolors = ["#7c7c7c", "#9d2a2a", "#26a82f"],
legendlabels = ["Blue", "Red", "Green"];
div.innerHTML += '<div class="legend-inner-top">' + '<div class="legend-inner-top-m" style="padding-top: 3px color: #e3e3e3;"><strong style="color: #e3e3e3">Legend</strong></div>' + '<div class="legend-inner-top-m" style="float: right;"><button type="button" class="btn btn-xs btn-legend closeLegend"></button></div>' + '</div>' + '<div class="legend-inner-bottom">'
if (map.hasLayer(jungle)) {
// loop through our density intervals and generate a label with a colored square for each interval
for (var i = 0; i < legendcolors.length; i++) {
div.innerHTML +=
'<div style="margin-top: 10px;"><i style="background:' + legendcolors[i] + '"></i>' + legendlabels[i] + "</div>";
}
}
if (map.hasLayer(tropical)) {
div.innerHTML += '<i><img src="assets/img/legend-tropical.png" alt="Tropical Icon" height="18" width="18"></i>' + 'Tropical' + "<div style='margin-top: 10px;'></div>";
}
if (map.hasLayer(forest)) {
div.innerHTML += '<i><img src="assets/img/legend-forest.png" alt="Forest Icon" height="18" width="18"></i>' + 'Forest' + "<div style='margin-top: 10px;'></div>";
}
div.innerHTML += '</div>'
return div;
}
dynamicmapLegend.addTo(map);
}
How to display multiples of imported html copies?
I would like to make attempt for multiple html imports through a javascript/ jQuery. However, I don't find there are any examples on the internet. Possibly because the html import technology is emerging.
In fact, I made an attempt. However, this does not have to be the guidelines.
<link rel="import" class="note-import" href="blah.html" />
<div id="notes">
<!-- Put it in here -->
</div>
<script>
var links = document.getElementsByClassName('note-import');
for (var i = 0; i < links.length; i++) {
var cont = document.head.importNode(links, true);
document.getElementById('notes').appendChild(cont);
}
</script>
The code means I want to display the html(s) (whom are divs with styles and so on) into the div with id notes.
Convert jQuery 1.10.1 to jQuery Mobile Structure
I would like to know if it is possible to change the codes under http: //jsfiddle.net/t5Hxk/5/ , which is written in jQuery 1.10.1 into a jQuery mobile code?
Sorry for the really stupid question, but I am really desperate to get the features under that fiddle file up in JQM format. And I have absolutely zero programming background.
I ask this question is because no one reply my question on: JQuery Mobile multiple level (3 or 4 levels) Nested Listview with JSON Data
Would really appreciate any forms of help / tips as I really can't proceed in working on my project.....
Thank you very much in advance! :)
JQuery UI Sortable: Save keys with sort order
I am using this code to save my JQuery UI sort order:
$(function() {
$('#sortable').sortable({
update: function (event, ui) {
var data = $(this).sortable('serialize');
$.ajax({
data: data,
type: 'POST',
url: '/sort.php'
});
}
});
$( "#sortable" ).disableSelection();
});
This produces an array of numbers. Let's say I also want to save keys with the numbers, based on tags in my list items.
So for example a sorted list such as:
<ul id='sortable'>
<li id='item-3' name='special'><image src='special.jpg'></li>
<li id='item-1' name='normal'><image src='normal.jpg'></li>
<li id='item-2' name='extraordinary'><image src='extraordinary.jpg'></li>
</ul>
Would produce this array in PHP:
$item['special'] = 3;
$item['normal'] = 1;
$item['extraordinary'] = 2;
I know how to access the tags with JQuery but not how to serialize these into an array to pass to my PHP script along with the sorted numbers. Help!
Angularjs Form input text is always undefined
Here is my form
<form>
<input class="text_box1" type="text" name="email" ng-model="forget.email" >
<button style="width:auto" class="sign_up" ng-click="doForget(forget)">Get a Password</button>
</form>
Inside my app.js I have
.when('/forget', {
title: 'forget',
templateUrl: 'resources/views/forget.php',
controller: 'authCtrl'
})
And inside the authCtrl controller i tried to do the console of the input value.
$scope.doForget = function (customer) {
console.log($scope.email);
};
But i am getting the console as undefined always.
How can i get this value ?
Why the slider plugin show before it is ready to generate?
I use the jquery slider plugin "slippry" :
I followed the tutorial and write like this:
$(document).ready(function () {
$('#item').slippry();
});
</script>
And Html
<ul id="item">
<?php
foreach ($banner_list as $key => $banner) {
echo "<li>";
echo "<a href='#slide'" . $key . "><img src='" . site_url("banner/" . $banner["image_url"]) . "'></a>";
echo "</li>";
}
?>
</ul>
The problem is , there is a second that the slider show when it is not ready.
And in a second , it is generated and show like this
Also , if I press f5 then it will not have this problem (perharps cached?) but when I press the enter at address bar to enter the page again it has the same problem again. How to fix the problem ? Thanks
Browser back button is not working in IE
Hello, I have generated follow button script from below website.But it is showing issue in IE.Same IE issue exist in below url.Any helps
CKEditor bullets and numbers formatting
I have CKEditor in mode inline, and one of the problems I'm having is not getting the bullets and numbers (lists) not attached to color and/or font size.
- Is there a way to get around this ?
Mouse Wheel Zooming
so i'm working on a canvas that you can only drag a image from side to side and use the mouse wheel to re size the image by zooming in and out on it here is the code i have so far please feel free to ask any more details. I'm trying to find a way that's compact to do this and require minimum code.
-
body { margin: 0px; padding: 0px; }
<script type="text/javascript"> function drawImage(imageObj) { var stage = new Kinetic.Stage({ container: "container", width: 1800, height: 800 }); var layer = new Kinetic.Layer(); // image var image1 = new Kinetic.Image({ image: imageObj, x: stage.getWidth() / 2 - 896 / 1, y: stage.getHeight() / 2 - 255 / 2, width: 200, height: 157, draggable: true, dragBoundFunc: function (pos) { if (pos.x < this.minX); { } this.minX = pos.x; return { x: pos.x, y: this.getAbsolutePosition().y } } }); // add cursor styling image1.on('mouseover', function() { document.body.style.cursor = 'pointer'; }); image1.on('mouseout', function() { document.body.style.cursor = 'default'; }); layer.add(image1); stage.add(layer); } var imageObj = new Image(); imageObj.onload = function() { drawImage(this); }; imageObj.src = 'image1.png'; </script> </body> </html>
jQuery UI droppable not over
Code:
$("div.layout.lo-content > div.content").droppable(
{
over:function(e,ui)
{
alert("yes");
$(this).css("background-color","#FFFFFF");
},
drop: function(e, ui)
{
$(ui.draggable).appendTo($(this));
if($(this).hasClass("ui-sortable"))
{
$("div.content").sortable('refresh');
}
}
});
As you can see, when an element is dragged on top of the above element, its background colour will change.
Is there a way to make the background colour transparent if the element is not over the droppable container?
Such as:
{
notover: function(e,ui) { }
}
Javascript conflicting with html anchor
I'm currently creating a website which has a persistent header and footer. To cut down on code duplication, I use jquery to load the header.html and footer.html when each different page is loaded.
Each html page which uses this header and footer, loads it with the code below.
<!-- Header and footer loading -->
<script>
$(function() {
$("#header").load("header.html");
$("#footer").load("footer.html");
});
</script>
<div id="header">
(header.html content rendered here)
</div>
The best way to explain this next part is by going to the site I have linked. What I would like to do is have the drop down button take a user to the specific section of the equipment page from any other page on the website. As you can currently see, this function only works if the user is already on the equipment page.
From everything I've read, cross page anchors should be setup the same way as in-page anchors. Use <a href="equipment.html#anchorname></a> and then link it to the page with <a id="anchorname></a>. However, this approach is only working when the user is on the same page as the anchor. I'm pretty sure this is due to the timing of anchor mechanism and when the jQuery code runs.
My two questions are...
- Could someone explain the sequence of events that are taking place which are causing my anchor not to work.
- What do I need to do in order to get my cross-site anchors to work properly?
Thanks and let me know if you need specific code snippets or have any questions.
Page load as you scroll without DB integration
On my website, we have a lot of date loading up when it is launched (something like a feed on facebook, people posting items). I want to implement infinit scroll, or load as you scroll option. Is there anyway to do this without a database integration? If so how, if not, we currently are using sql server for our DB. Any good examples that utilize sql server? Most examples use mysql.
Copy multiple input fields to other matching input fields with jQuery/Javascript
I have a dummy form and the actual form in which at some point I want to copy all the input values from the dummy form across to the real form. The dummy fields will have the same names as the real form (so I can match them up).
So in dummy form:
<input name="item1" value="field1" />
<input name="item2" value="field1" />
<input name="item3" value="field1" />
and in real form:
<input name="item1" value="" />
<input name="item2" value="" />
<input name="item3" value="" />
I assume I'll need to iterate over each input in dummy form (using jQuery .each() ?) while collecting the name and value in an JS object. Then iterate over each input in the real form, matching the name as the selector and setting the value (perhaps this can be done in the one .each() function ???)
I've started with the following code which only grabs the values (and index) into an array, but because I need two values (name and value, and index is irrelevant) I assume I'll need an object not an array, but really not sure where to begin with that.
var inputValues = [];
$("#dummyForm input").each(function() {
inputValues.push($(this).val());
});
Any help or advice much appreciated.
Can't use this to point a selected element with jQuery
Why this JS does not apply my class to the element please ?
<input type="password" name="customer-new-password" class="form-control">
<script>
if($("input[name='customer-new-password']").val()=='') {
$(this).addClass('required');
}
else {
$(this).removeClass('required');
}
</script>
Thanks.
Javascript wont update div rails 4
Hello a rails 4 newbie here. I cant seem to get ajax to update the view. I am at a loss. I can get an alert to pop up when click the +1 link in the view but I can't get the view to update (show the votes) the span with id="ajaxed", even though the database is updating. I have read the rails guides on ajax and look at about 6 videos on youtube on how to do this and it seems right to me but doesn't work for me. here is my html:
<tbody>
<% @topics.each do |topic| %>
<tr>
<td><%= topic.title %></td>
<td><%= topic.description %></td>
<td><span id="ajaxed"><%=pluralize(topic.votes.count, "vote")%></span></td>
<td><%= link_to "+1", upvote_topic_path(topic), id: "upvote", remote: true, method: :post%></td>
<td><%= pluralize(topic.downvotes.count, "downvote") %></td>
<td><%= link_to "-1", downvote_topic_path(topic), method: :post %></td>
<td><%= link_to 'Show', topic %></td>
<td><%= link_to 'Edit', edit_topic_path(topic) %></td>
<td><%= link_to 'Destroy', topic, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
Here is my controller:
def upvote
@topic = Topic.find(params[:id])
@topic.votes.create
#redirect_to topics_path
respond_to do |format|
format.html { redirect_to topics_path }
format.js
end
end
here is my upvote.js.erb:
$('#ajaxed').text('<%=pluralize(topic.votes.count, "vote")%>');
BTW any other form of javascript or jquery that I do on the upvote.js.erb seems to work, it just wont update my '#ajaxed' span. I also tried .html and even straight js document.getElementById("ajaxed").innerHTML = '<%=pluralize(topic.votes.count, "vote")%>', this gives me unwanted results. Any help would be greatly appreciated. Thanks!!!
Dropdown changing value when selected
I have 5 cities (phil, germany, usa, china and russia) and this 5 cities are stored from database and I also have 5 dropdown having those 5 cities as there values.
What i want to happened is this, if the user select germany on dropdown 1, germany value on other dropdowns shouldn't exist anymore. Meaning, germany will be remove automatically on options of the other dropdown.
Can anyone know's how to make this possible on codeigniter?
At the moment i have this initial code http://ift.tt/1HwibEe
Is there's a need to use jquery or javascript to make this happened? Thanks
Jquery Sometime Working fine and sometime giving "Uncaught TypeError: undefined is not a function"
Here is my script tag
Sometime It loaded all the pages, sometime few and giving the following error: Uncaught TypeError: undefined is not a function
Earlier I searched on the web about the same error, someone suggested to use jQuery.noConflict(),jQuery.noConflict(true)
I stored the value of jquery no conflict int a variable named j and replaced the jquery sign($) with j, but it didn't work. Also tried with passing a true value to no conflict as suggested by someone else on the forums, but no solution the problem.
Any help appreciated!
<script>
//var j = jQuery.noConflict(true);
$(document).ready(function () {
$('#loading_status').hide();
var total_row =946;
var per_page = 15;
var total_page = parseInt(total_row / per_page);
var current_page = 0;
var loadable = true;
var loadNextPage = function (start, rows) {
$('#loading_status').show();
$.ajax({
url: 'http://ift.tt/1dz7kgE',
type: 'post',
data: {
page: 0,
start: start,
records: rows
},
success: function (result) {
$("#flushed").append(result);
loadable = true;
$('#loading_status').hide();
},
error: function (xhr, status, error) {
alert("Error code: " + xhr.status + "\n\n\nError message: " + xhr.responseText);
}
});
};
loadNextPage(current_page, per_page);
$(window).scroll(function () {
if (($(window).scrollTop() + $(window).height()) >= ($(document).height() - 1000) && current_page < total_page && loadable == true) {
loadable = false;
current_page++;
var start = (current_page * per_page) + 1;
loadNextPage(start, per_page);
}
});
});
</script>
Flot change bar opacity on hover
The default flot bar chart changes from opacity:.5 to an opacity:1 on hover. I would like to invert this but I can not seem to find anyone that has done this. This it the code that I am currently using.
$.extend(true, opts.flot, {
series: {
points: { show: false },
bars: {
align : 'center',
order : (opts.stacked) ? null : true,
show : true,
border : false,
fill : 1,
fillColor : null,
horizontal : opts.horizontal,
barWidth : (opts.stacked) ? 0.6 : 0.6 / opts.data.length,
lineWidth : 0
},
lines: { show: false },
pie: { show: false }
}
});
I want Fancybox to work on my divs - do I need to edit html?
I have some 'item' class divs, which are grey boxes with an image and a caption inside them. When they're clicked, I want them to appear bigger.
I have applied fancybox, but nothing happens. I have added all the relevant files into the html.
Here's the html code:
<div class="container">
<div class="item">
<img src="photo.jpg">
<p>Image caption</p>
</div>
<div class="item">
<img src="photo.jpg">
<p>Image caption</p>
</div>
<div class="item">
<img src="photo.jpg">
<p>Image caption</p>
</div>
<div class="item">
<img src="photo.jpg">
<p>Image caption</p>
</div>
</div>
Submit an input box OR a select box (not both)
I want to have the option for my users to submit a form that they have the option to either use either the select box or the input text box, but not both. Here is my form code:
<!-- Text input-->
<div id="incident-type" class="control-group">
<label class="control-label" for="textinput">Incident Type (Use this box or the common incident box)</label>
<div class="controls">
<input id="textinput" name="incident_type" type="text" class=" form-control">
</div>
</div>
<!-- Select Box -->
<div id="incident-control-box" class="control-group">
<label class="control-label" for="textinput">Common Incidents (Use this box or the incident type box)</label>
<div class="controls">
<select onclick="hideInputBox()" id="textinput incident-type1" name="incident_type" type="text" class=" form-control" >
<option value="blank"></option>
<option value="AFA Commercial">AFA Commercial</option>
<option value="AFA Residential">AFA Residential</option>
<option value="MVA W/Injuries">MVA W/Injuries</option>
<option value="Gas Leak Outside">Gas Leak Outside</option>
<option value="Gas Leak Inside">Gas Leak Inside</option>
<option value="Investigation">Investigation</option>
<option value="Possible Structure Fire">Possible Structure Fire</option>
</select>
</div>
</div>
Then here is my code from my PHP where it gets the input boxes of the form:
$incident_type = $row['incident_type'];
The problem I run into is that I want either one of them to submit depending on what the user chooses to fill out. Currently only the select input works, not the text box input also.
JavaScript Multiple Arrays in Object
I'm trying to display all of the items in my list below. I organized them as such in order to filter them out.
For example, I want all the titles to be separate from the array items they contain (so that the titles will display as headers and the items as regular text.
Here is my code so far:
var general = {
"Hardcover" : {
["Book A",4],
["Book B",6],
["Book C",5]
}
// ... other options
};
for (var title in general) {
var title = ...; // assign the title variable
$('body').append("<h2>" + title + "</h2>");
for(var items in title) {
// assign item variables separately
var itemTitle = ...;
var itemPrice = ...;
$('body').append(itemTitle + ": $" + itemPrice);
}
}
So the final output would look something like:
Hardcover
Book A: $4
Book B: $6
Book C: $5
I made a quick fiddle below with my full list: http://ift.tt/1GOX7nK
Responsive Image Grid with Different Heights and Widths
I need to be able to create a responsive image grid with different image widths, (link to an image below.)
Here's what I have right now.
This ^ fits and looks good on my 27" iMac, but isn't responsive, and I haven't been able to figure out a good solution for it due to the varying heights and widths. Masonry.js didn't work for me as I'm developing this site in Wordpress and the grid is created dynamically. I need to know if there is another option for this. Thanks to all in advance!
Displaying List from mysql data using jquery mobile
Im trying to get my squery mobile app to show certain data of mysql in a listview mode. It seems to be something wrong as nothing happens when I try it.
Here is my html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Watto</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="../css/app.css" rel="stylesheet" />
<link href="../css/themes/2/watto.min.css" rel="stylesheet" />
<link href="../css/themes/2/jquery.mobile.icons.min.css" rel="stylesheet" />
<link href="../lib/jqm/jquery.mobile.structure-1.4.5.min.css" rel="stylesheet" />
<script src="../js/listaplanesnuevos.js"></script>
<script src="../lib/jquery/jquery-2.1.4.min.js"></script>
<script src="../lib/jqm/jquery.mobile-1.4.5.js"></script>
<script src="../services/getplanes.php"></script>
<link rel="apple-touch-icon" href="../img/apple-touch-icon.png" />
<link rel="apple-touch-icon-precomposed" href="../img/apple-touch-icon.png"/>
</head>
<body>
<!----------PLANES NUEVOS ------------>
<div data-role="page" id="planesnuevos">
<div data-role="header" data-position="fixed">
<h1>Planes Nuevos</h1>
</div> <!----HEADER---->
<div role="main" class="ui-content">
<ul id="listaplanesnuevos" data-role="listview" data-filter="true"></ul>
</div> <!------ CONTENT ----->
<div data-role="footer">
<div data-role="navbar">
<ul>
<li><a href="#planesnuevos" data-icon="home" class="ui-btn-active"></a></li>
<li><a href="#search" data-icon="search"></a></li>
<li><a href="#chooser" data-icon="eye" data-iconpos="right"></a></li>
<li><a href="#location" data-icon="location"></a></li>
<li><a href="../settings" data-icon="gear"></a></li>
</div>
</div>
</body>
</html>
Here is my JavaScript:
var serviceURL = "http://localhost/directory/app/watto/services";
var planes;
$('#planesnuevos').bind('pageinit', function(event) {
getListaPlanes();
});
function getListaPlanes() {
$.getJSON(serviceURL + 'getplanes.php', function(data) {
$('#listaplanesnuevos li').remove();
resplanes = data.items;
$.each(resplanes, function(index, plan) {
$('#listaplanesnuevos').append('<li><a href="detallesplan.html?id=' + plan.folio + '">' +
'img src="pics/' + plan.foto + '"/>' +
'<h4>' + plan.nombre + '</h4>' +
'<p>' + plan.descripcion + '</p></a></li>');
});
$('#listaplanesnuevos').listview('refresh');
});
}
and here is the PHP file
<?PHP
include 'config.php';
$sql = "SELECT `folio`, `nombre`, `descripcion`, `foto` FROM `Planes` GROUP BY `folio` ORDER BY `folio`";
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->query($sql);
$planes = $stmt->fetchAll(PDO::FETCH_OBJ);
$dbh = null;
echo '{"items":'. json_encode($planes) .'}';
} catch(PDOException $e) {
echo '{"error":{"text":' . $e->getMessage() . '}}';
}
?>
I don't know what is wrong, please help as im new to this.
Thanks!
How to get a different window's html with javascript
I would like to open a new window using a url, grab its html as a string and display it in the console of the original window.
From How to get element and html from window.open js function with jquery , I tried:
console.log('response', url)
var popup = window.open(url, '_blank', 'width=500,height=500');
popup.onload = function() {
setTimeout(function(){ console.log( 'hi',popup.document.documentElement.outerHTML) }, 2000);
}
The popup window is created, but I don't see the popup's html in the original window's console.
What am I doing wrong?
jssor onclick open larger version
Is it possible using jssor to click on a photo in the slideshow and on click make it open a larger photo (responsive/mobile-friendly), e.g. in a popup?
Currently I'm using the following code:
<script>
jQuery(document).ready(function ($) {
var _SlideshowTransitions = [{ $Duration: 500, $Opacity: 2, $Brother: { $Duration: 1000, $Opacity: 2 } }];
var options = {
$FillMode: 1,
$DragOrientation: 3,
$AutoPlay: true,
$AutoPlayInterval: 5000,
$SlideshowOptions: {
$Class: $JssorSlideshowRunner$,
$Transitions: _SlideshowTransitions,
$TransitionsOrder: 1,
$ShowLink: true
}
};
var jssor_slider1 = new $JssorSlider$('artikelphoto', options);
});
</script>
<div u="slides" style="position: absolute; overflow: hidden; left: 0px; top: 0px; width: 200px; height: 200px;">
<div><img u="image" src="/1.jpg" /></div>
<div><img u="image" src="/2.jpg" /></div>
</div>
How do I make this code refresh every minute?
How do I make this code refresh every minute?
<script type="text/javascript">
$j(document).ready(function () {
$j('#left-box').load('pages/box.php');
});
</script>
I want it to refresh every 1 minute I've tried other stuff cant do it
minimum set of module/methonds in jquery code for selector
I am reading jquery code now. I found the following methods are suitable for cross platform programming. (desktop, web browser and mobile app)
$(selector)
$.ajax() <----------I am not sure if this is veryuseful
$(selector).find()
$(selector).bind()
$(selector).unbind()
$(selector).delegate()
$(selector).remove()
$(selector).attr()
$(selector).html()<-----I am not sure if this is veryuseful
I mean that I prefer the javascript native code to process logic bussiness except some selector/dom function. This means that I even can use the same logic code in QT/QML.
Is there is minimum set of module/methonds for the methods above?
Your comment welcome
JQuery Mobile multiple level (3 or 4 levels) Nested Listview with JSON Data
Can anyone provide me a simple demo of jQuery Mobile, 3 to 4 levels of dynamic nested listview/treeview that takes in list details from nested JSON data present in the same HTML file?
Just 1 or 2 ul/li will do, I will try my best to figure the remaining myself!
I am new to both JSON and jQuery. I have spent plenty of time going through several examples in order to get this done.
These are a few links that I have tried to follow but failed as I do not know how to convert another version of jQuery to jQuery Mobile:
Below is my current JSON structure that I manage to produce:
var info = {
[{
"id":1,
"name":"Folder A",
"img":"img/1.png",
"branch":[{
"id":2,
"name":"Folder A.1",
"my-hash":"hash-2",
"my-url":"sample.html?request=page-2"
},
{
"id":3,
"name":"Folder A.2",
"my-hash":"hash-3",
"my-url":"sample.html?request=page-3"
},
{
"id":4,
"name":"file a.1",
"my-hash":"hash-4",
"my-url":"sample.html?request=page-4"
},
{
"id":5,
"name":"file a.2",
"my-hash":"hash-5",
"my-url":"sample.html?request=page-5"
}],
"my-hash":"hash-1",
"my-url":"sample.html?request=page-1"
},
{
"id":6,
"name":"Folder B",
"img":"img/6.png",
"my-hash":"hash-6",
"my-url":"sample.html?request=page-6"
},
{
"id":7,
"name":"Folder C",
"img":"img/7.png",
"branch":[{
"id":8,
"name":"Folder C.1",
"branch":[{
"id":9,
"name":"Folder C.1.1",
"my-hash":"hash-9",
"my-url":"sample.php?request=page-9"
},
{
"id":10,
"name":"Folder C.1.2",
"my-hash":"hash-10",
"my-url":"sample.html?request=page-10"
},
{
"id":11,
"name":"file c.1.1",
"my-hash":"hash-11",
"my-url":"sample.html?request=page-11"
}],
"my-hash":"hash-8",
"my-url":"sample.html?request=page-8"
},
{
"id":12,
"name":"file c.1",
"img":"img/12.png",
"my-hash":"hash-12",
"my-url":"sample.html?request=page-12"
}],
"my-hash":"hash-7",
"my-url":"sample.html?request=page-7"
},
{
"id":13,
"name":"file a",
"img":"img/13.png",
"my-hash":"hash-13",
"my-url":"sample.html?request=page-13"
},
{
"id":14,
"name":"file b",
"img":"img/14.png",
"my-hash":"hash-14",
"my-url":"sample.html?request=page-14"
},
{
"id":15,
"name":"file c",
"img":"img/15.png",
"my-hash":"hash-15",
"my-url":"sample.html?request=page-15"
}]
Ok, the question is, provided that my JSON data is correctly structured, can anyone help me in writing a jQuery Mobile script that dynamically takes in data and produce list result as shown in this JQM demo
I will explain more if this is unclear. Will really appreciate any help. Thanks!