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:
This worked and looks rather clean.
Thanks.