Validate a value changed with Jeditable - javascript

I'm not quite good at javascript and ajax, so I ask you for help. I use Symfony2 and Twig and I have a field which I change with jediable but its value should be unique. So I check this in the controller action, but I can't succeed in making the app to act normally. I tried a lot of things and the closest to the result I want is this:
if (count($same) == 0) {
// add to database
} else {
$response = new Response();
$response->setContent('<div class="alert alert-error">
<button type="button" class="close" data-dismiss="alert">OK</button>
<strong>This value is already used!</strong> Please choose another.
</div>');
$response->send();
which outputs this nice error:
but when I click OK, the jeditable pluging is still working, and the whole error becomes editable, so the value of the input field contains all the HTML set in $response->setContent()
Because the the whole block
<div class="alert alert-error">
<button type="button" class="close" data-dismiss="alert">OK</button>
<strong>This value is already used!</strong> Please choose another.
</div>
is in the div with the class '.edit' when I click it, it becomes editable and contains this whole block. What I want is when the user clicks on the alert generated in the controller to return to input field from jeditable with a value as the original name of the category before he started to edit or with empty value.
This is my .js file but it doesn't make the input field empty (but it prints wokring) :(
$(document).ready(function(){
$('.edit').editable(path, {
cancel : 'Cancel',
submit : 'Save',
tooltip : 'Click to edit'
});
$('.bla').on('click','.alert', function(){
console.log('working');
$("input[type=text]").hmtl('');
});
});
HTML
<span class="right-spacer"><strong id="{{cat.id}}"class="edit bla">{{ cat.name }}</strong>
Any ideas for solution?

If I understand, your popup error is created dynamically when someone click on the button "Save" with an invalid value, this means that the pop-up does not exists at the $(document).ready time. This is why this part:
$('.alert').on('click', function(){
$("input[type=text]").val('');
});
Will never be executed. If you want this function to work, you will need to use delegation, as you use Jquery this will be pretty easy.
Instead of $('.alert').on('click', function(){
You will have to use something like $('body').on('click','.alert', function(){
Where body is an element that is a parent of .alert, for exemple if you know your pop-up will be created inside a div with the id of first_div(Something like <div id="first_div">) You would put instead $('#first_div').on('click','.alert', function(){
This means that the div will listen to the click events inside him, so the closer he is to the pop-up the more efficient it is.

I think this was missing,
if (count($same) == 0) {
// add to database
// clear the content on form.
//$("input[type=text]").html('');//it should be html not **hmtl**
}
Try and reply if not done..
This should do..

Related

javascript prepending an action to a function that is bound to an event

I have a page with a button, I have a binding on the button that executes some ajax calls sending some data.
The code with the binding is rather generic and reused in several other spots in the application. So I can't change its current behaviour (I could change it in a way that won't affect other users of this).
I have now a requirement to change the behaviour of one of the pages that use this binding (i.e. I shouldn't change the binging in a way that breaks the other pages).
Now I need the button in a specific page to not submit the data in case some other conditions are not met. (in specific instead of submitting, I need to show a modal, with a double check if they really want to complete the submission)
I made an executable snippet which explains it:
$('button').click(function (e) {
$('ul').append('<li>submitting data</li>');
});
$('button').click(function (e) {
if($(this).data('value') != 'ready') {
$('ul').append('<li>condition not met, data not submitted</li>')
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
When the button is clicked, I want the data
to be submitted only if the condition is not met.
</p>
<p>
In this example I need 'condition not met'
to be printed, and not 'submitting data'.
</p>
<button data-value='not-ready'>
content
</button>
<ul>
</ul>
I need that this specific page doesn't submit the data in case the condition is not met.
How could I get this?
Not sure if this is what you're looking for - done with the assumption that you might not want to change the structure of the button's HTML. You could set one of its outer containers to something you could test for - and then along those lines, you could also set a dynamic validation function to call for the button inside the container.
$('button').click(function(e) {
if ($(this).closest('.validate-extra').length > 0) {
if ($(this).closest('.validate-extra').data('fn')) {
return window[$(this).closest('.validate-extra').data('fn')]();
} else {
console.error('no special validation function in scope!');
}
} else $('ul').append('<li>submitting data</li>');
});
function val1() {
console.log('running function val1()');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
When the button is clicked, I want the data to be submitted only if the condition is not met.
</p>
<p>
In this example I need 'condition not met' to be printed, and not 'submitting data'.
</p>
<button data-value='not-ready'>
content
</button>
<div class='validate-extra' data-fn='val1'>
<button data-value='not-ready'>
content
</button>
</div>
<ul>
</ul>
Following #aleksG suggestion in the comments I ended up with quite a bit of changes, but mainly:
move the code that does the data submission to a function, that can be called from anywhere
have each of the pages that use that function load the binding independently (the binding was there globally earlier)
have a new binding on a new css class that handles the validations before (eventually) calling the code submission
This worked and looks rather clean.
Thanks.

Disabling a button via JS if a specific element ID appears on page

I am trying to use JS to change an add to cart button to be disabled if our inventory level (displayed on the front end in a <span>) is "out of stock". This JS is already set up on our site for changing button behaviour for variants (code at the bottom of the post) and so if I can integrate an additional conditional rule using our inventory <span> that would be amazing.
Here's the HTML for when the out of stock message appears:
<span class="LocationNoStock">Currently Sold Out</span>
I honestly have almost zero experience with JS so all I know is that I can look for elements by class name:
(document.getElementsByClassName("LocationNoStock")
Basically I want to add logic that dictates:
if class 'LocationNoStock' exists then disable 'add-to-cart' button
Any help that can be offered would be much appreciated! If it helps, our current JS for modifying the add-to-cart button is as follows - if an additional rule to search for the <span> could be inserted and mimic the behaviour that would be amazing!
updateCartButton: function(evt) {
var variant = evt.variant;
if (variant) {
if (variant.available) {
// Available, enable the submit button and change text
$(selectors.addToCart, this.$container).removeClass(classes.disabled).prop('disabled', false);
$(selectors.addToCartText, this.$container).html(theme.strings.addToCart);
} else {
// Sold out, disable the submit button and change text
$(selectors.addToCart, this.$container).addClass(classes.disabled).prop('disabled', true);
$(selectors.addToCartText, this.$container).html(theme.strings.soldOut);
}
} else {
// The variant doesn't exist, disable submit button
$(selectors.addToCart, this.$container).addClass(classes.disabled).prop('disabled', true);
$(selectors.addToCartText, this.$container).html(theme.strings.unavailable);
}
},
Your using jquery $(...) so you could do the following, look for .LocationNoStock if it's found then disable the .add-to-cart button.
if ($('.LocationNoStock').length) $('.add-to-cart').attr('disabled', 'disabled')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="LocationNoStock">Currently Sold Out</span>
<button type="button" class="add-to-cart">Add to Cart</button>
To disable buttonin javascript on load, can be done by setting attribute of the element
Example :
setAttribute("style","color:red")
In your case you are fetching element using class "add-to-cart" which gives htmlcollection so using index you can access the button element and then using setAttribute function of javascript, can set particular properties.
Try this:
$(document).ready(function(){
if (document.getElementsByClassName("LocationNoStock") != null){
var element = document.getElementsByClassName("add-to-cart");
element[0].setAttribute("disabled", "");
}
});

Rails javascript; alert to fire when leaving a field

My ultimate goal is to add some validation to a set of date fields. However, my javascript sucks, so I'm starting small.
I am starting out by trying to get an alert message when a user leaves a field.
(For simplicity I'm just doing it all in my view...) Heres what I go to work...
# html.erb-template
<div class="from_date">
From Date
<input type="text" id="from_date" name="from_date"></input>
</div>
<script>
$("#from_date").blur( function() {
alert("boom!");
});
</script>
Your code seems to be fine - problem is that class and id are named the same, but you want to watch the input field not the surrounding div.
I just made a fiddle from your script and changed
the listener to be attached to the input field's id - and it's working.
the alert into a console.log
see
$("#from_date").blur(function() {.....
// instead of
$(".from_date").blur(function() {.....

JavaScript hide element function

I have a form where the user can select a generic auto-population based on checking a radio button. When the user checks the auto-populate radio button, the fields are auto populated with the data and then the fields become disabled.
In this first part of the function, I pass the auto-filled data:
$('#myOptions').click(function()
$('#value1').val("Auto-filled data");
$('#Value2').val("Auto-filled data");
$('#Value3').val("Auto-filled data");
In this second part, I am disabling the html inputs
// now i am disabling the html inputs:
$('#Value4').prop("disabled", true);
$('#Value5').prop("disabled", true);
$('#value6').prop("disabled", true);
Suppose I have another field with an ID of "Value7" in the form, that I would like to hide from the user interface as part of this function.
How can I hide the "Value7" input upon function triggering? I appreciate the help, I am very new to JavaScript, though I find it very exciting!
Using jquery:
To hide
jQuery('#Value7').hide() or jQuery('#Value7').css("display","none")
To show the element back
jQuery('#Value7').show() or jQuery('#Value7').css("display","block")
or pure js:
javascript hide/show element
Try this javascript:
if you want disable:
document.getElementById('#Value7').setAttribute("disabled","disabled");
if you want enable:
document.getElementById('#Value7').removeAttribute('disabled');
if you want to hide :
document.getElementById('#Value7').css("display","none");
if you want to show:
document.getElementById('#Value7').css("display","block");
I am not getting what are you trying to ask actualy .
Let me know if this helps -
$("Value7").hide()

Show Input Box on Check

You can see in the paper form attached what I need to convert into a web form. I want it to show the check boxes and disable the input fields unless the user checks the box next to it. I've seen ways of doing this with one or two elements, but I want to do it with about 20-30 check/input pairs, and don't want to repeat the same code that many times. I'm just not experienced enough to figure this out on my own. Anyone know anywhere that explains how to do this? Thanks!
P.S. Eventually this data is all going to be sent through an email with PHP.
I don't think this is a good idea at all.
Think of the users. First they have to click to enter a value. So they always need to change their hand from mouse to keyboard. This is not very usable.
Why not just give the text-fields? When sending with email you could just leave out the empty values.
in your HTML :
//this will be the structure of each checkbox and input element.
<input type="checkbox" value="Public Relations" name="skills" /><input type="text" class="hidden"/> Public Relations <br/>
in your CSS:
.hidden{
display:none;
}
.shown{
display:block;
}
in your jQuery:
$('input[type=checkbox]').on('click', function () {
// our variable is defined as, "this.checked" - our value to test, first param "shown" returns if true, second param "hidden" returns if false
var inputDisplay = this.checked ? 'shown' : 'hidden';
//from here, we just need to find our next input in the DOM.
// it will always be the next element based on our HTML structure
//change the 'display' by using our inputDisplay variable as defined above
$(this).next('input').attr('class', inputDisplay );
});
Have fun.
Since your stated goal is to reduce typing repetitive code, the real answer to this thread is to get an IDE and the zen-coding plug in:
http://coding.smashingmagazine.com/2009/11/21/zen-coding-a-new-way-to-write-html-code/
http://vimeo.com/7405114

Categories